iOS DES ECB模式對稱式加密解密

來源:互聯網
上載者:User

    最近忙於android和iOS的項目,寫完了android的DES 的ECB模式加密解密(相關串連:http://blog.csdn.net/vipa1888/article/details/8086037),又回到了Ios上面,因為本人也是最近今年開始研究ios的,所以Ios上面好多東西都不懂,進過了半年的研究,終於吧ios的DES 的ECB模式對稱式加密解密搞定了,本人遇到的問題很嚴重的問題,網上寫的好多16進位數轉化位位元組都有問題的,經過本人研究發現他們有一個地方寫錯了,導致解密後的NSString
位null,My Code已經修複了這個問題,下面貼出原始碼供大家參考:

首先貼出加密類的標頭檔:
////  DesUtil.h//  Author:spring sky//  QQ:840950105//  Email:vipa1888@163.com//#import <Foundation/Foundation.h>@interface DesUtil : NSObject/** DES加密 */+(NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key;/** DES解密 */+(NSString *) decryptUseDES:(NSString *)plainText key:(NSString *)key;@end

加密類的實作類別:

////  DesUtil.m//  Author:spring sky//  QQ:840950105//  Email:vipa1888@163.com//#import "DesUtil.h"#import <CommonCrypto/CommonCryptor.h>#import "ConverUtil.h"@implementation DesUtilstatic Byte iv[] = {1,2,3,4,5,6,7,8};/* DES加密 */+(NSString *) encryptUseDES:(NSString *)clearText key:(NSString *)key{    NSString *ciphertext = nil;    NSData *textData = [clearText dataUsingEncoding:NSUTF8StringEncoding];    NSUInteger dataLength = [clearText length];    unsigned char buffer[1024];    memset(buffer, 0, sizeof(char));    size_t numBytesEncrypted = 0;            CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,                                          kCCOptionECBMode,                                          [key UTF8String], kCCKeySizeDES,                                          iv,                                          [textData bytes], dataLength,                                          buffer, 1024,                                          &numBytesEncrypted);    if (cryptStatus == kCCSuccess) {        NSLog(@"DES加密成功");        NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];        Byte* bb = (Byte*)[data bytes];        ciphertext = [ConverUtil parseByteArray2HexString:bb];    }else{        NSLog(@"DES加密失敗");    }    return ciphertext;}/** DES解密 */+(NSString *) decryptUseDES:(NSString *)plainText key:(NSString *)key{    NSString *cleartext = nil;    NSData *textData = [ConverUtil parseHexToByteArray:plainText];    NSUInteger dataLength = [textData length];    unsigned char buffer[1024];    memset(buffer, 0, sizeof(char));    size_t numBytesEncrypted = 0;            CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,                                          kCCOptionECBMode,                                          [key UTF8String], kCCKeySizeDES,                                          iv,                                          [textData bytes], dataLength,                                          buffer, 1024,                                          &numBytesEncrypted);    if (cryptStatus == kCCSuccess) {        NSLog(@"DES解密成功");        NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];        cleartext = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];    }else{        NSLog(@"DES解密失敗");    }    return cleartext;}@end
下面是轉碼類,主要是16進位和位元組的轉化 標頭檔:
////  ConverUtil.h//  Author:spring sky//  QQ:840950105//  Email:vipa1888@163.com//#import <Foundation/Foundation.h>@interface ConverUtil : NSObject/** 64編碼 */+(NSString *)base64Encoding:(NSData*) text;/** 位元組轉化為16進位數 */+(NSString *) parseByte2HexString:(Byte *) bytes;/** 位元組數組轉化16進位數 */+(NSString *) parseByteArray2HexString:(Byte[]) bytes;/* 將16進位資料轉化成NSData 數組 */+(NSData*) parseHexToByteArray:(NSString*) hexString;@end

實作類別:

////  ConverUtil.m//  Author:spring sky//  QQ:840950105//  Email:vipa1888@163.com//#import "ConverUtil.h"@implementation ConverUtilstatic const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";/** 64編碼 */+(NSString *)base64Encoding:(NSData*) text{    if (text.length == 0)        return @"";        char *characters = malloc(text.length*3/2);        if (characters == NULL)        return @"";        int end = text.length - 3;    int index = 0;    int charCount = 0;    int n = 0;        while (index <= end) {        int d = (((int)(((char *)[text bytes])[index]) & 0x0ff) << 16)        | (((int)(((char *)[text bytes])[index + 1]) & 0x0ff) << 8)        | ((int)(((char *)[text bytes])[index + 2]) & 0x0ff);                characters[charCount++] = encodingTable[(d >> 18) & 63];        characters[charCount++] = encodingTable[(d >> 12) & 63];        characters[charCount++] = encodingTable[(d >> 6) & 63];        characters[charCount++] = encodingTable[d & 63];                index += 3;                if(n++ >= 14)        {            n = 0;            characters[charCount++] = ' ';        }    }        if(index == text.length - 2)    {        int d = (((int)(((char *)[text bytes])[index]) & 0x0ff) << 16)        | (((int)(((char *)[text bytes])[index + 1]) & 255) << 8);        characters[charCount++] = encodingTable[(d >> 18) & 63];        characters[charCount++] = encodingTable[(d >> 12) & 63];        characters[charCount++] = encodingTable[(d >> 6) & 63];        characters[charCount++] = '=';    }    else if(index == text.length - 1)    {        int d = ((int)(((char *)[text bytes])[index]) & 0x0ff) << 16;        characters[charCount++] = encodingTable[(d >> 18) & 63];        characters[charCount++] = encodingTable[(d >> 12) & 63];        characters[charCount++] = '=';        characters[charCount++] = '=';    }    NSString * rtnStr = [[NSString alloc] initWithBytesNoCopy:characters length:charCount encoding:NSUTF8StringEncoding freeWhenDone:YES];    return rtnStr;}/** 位元組轉化為16進位數 */+(NSString *) parseByte2HexString:(Byte *) bytes{    NSMutableString *hexStr = [[NSMutableString alloc]init];    int i = 0;    if(bytes)    {        while (bytes[i] != '\0')        {            NSString *hexByte = [NSString stringWithFormat:@"%x",bytes[i] & 0xff];///16進位數            if([hexByte length]==1)                [hexStr appendFormat:@"0%@", hexByte];            else                [hexStr appendFormat:@"%@", hexByte];                        i++;        }    }    NSLog(@"bytes 的16進位數為:%@",hexStr);    return hexStr;}/** 位元組數組轉化16進位數 */+(NSString *) parseByteArray2HexString:(Byte[]) bytes{    NSMutableString *hexStr = [[NSMutableString alloc]init];    int i = 0;    if(bytes)    {        while (bytes[i] != '\0')        {            NSString *hexByte = [NSString stringWithFormat:@"%x",bytes[i] & 0xff];///16進位數            if([hexByte length]==1)                [hexStr appendFormat:@"0%@", hexByte];            else                [hexStr appendFormat:@"%@", hexByte];                        i++;        }    }    NSLog(@"bytes 的16進位數為:%@",hexStr);    return [hexStr uppercaseString];}/* 將16進位資料轉化成NSData 數組 */+(NSData*) parseHexToByteArray:(NSString*) hexString{    int j=0;    Byte bytes[hexString.length];     for(int i=0;i<[hexString length];i++)    {        int int_ch;  /// 兩位16進位數轉化後的10進位數        unichar hex_char1 = [hexString characterAtIndex:i]; ////兩位16進位數中的第一位(高位*16)        int int_ch1;        if(hex_char1 >= '0' && hex_char1 <='9')            int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48        else if(hex_char1 >= 'A' && hex_char1 <='F')            int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65        else            int_ch1 = (hex_char1-87)*16; //// a 的Ascll - 97        i++;        unichar hex_char2 = [hexString characterAtIndex:i]; ///兩位16進位數中的第二位(低位)        int int_ch2;        if(hex_char2 >= '0' && hex_char2 <='9')            int_ch2 = (hex_char2-48); //// 0 的Ascll - 48        else if(hex_char2 >= 'A' && hex_char1 <='F')            int_ch2 = hex_char2-55; //// A 的Ascll - 65        else            int_ch2 = hex_char2-87; //// a 的Ascll - 97                int_ch = int_ch1+int_ch2;        bytes[j] = int_ch;  ///將轉化後的數放入Byte數組裡        j++;    }    NSData *newData = [[NSData alloc] initWithBytes:bytes length:hexString.length/2];    NSLog(@"newData=%@",newData);    return newData;}@end
測試結果:

2012-10-18 19:58:41.592 [3356:707]
明文 = 1PALMPAY   key = 12345678

2012-10-18 19:58:41.599 [3356:707] DES加密成功

2012-10-18 19:58:41.601 [3356:707] bytes
16進位數為:0be9d717b1478b32

2012-10-18 19:58:41.603 [3356:707]
加密後的資料:0BE9D717B1478B32

2012-10-18 19:58:41.604 [3356:707] newData=<0be9d717 b1478b32>

2012-10-18 19:58:41.607 [3356:707] DES解密成功

2012-10-18 19:58:41.608 [3356:707]
解密後的資料:1PALMPAY



本人的工作內容主要是銀行金融方面,所以經常會使用到各種的加密解密,如果有需要協助的朋友可以聯絡我,如果我能搞定的,一定儘力而已!

歡迎轉載,但是必須保留著作權!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.