ecb ios 加密模式
2013-09-30 17:10:00 weixin_34198453 阅读数 10
//iOS DES  ECB 模式加密 
#import <CommonCrypto/CommonCryptor.h>


static Byte iv[] = {1,2,3,4,5,6,7,8};
+(NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key

 {
    
         NSString *ciphertext = nil;
    
         const char *textBytes = [plainText UTF8String];
    
         NSUInteger dataLength = [plainText length];
     

        unsigned char buffer[1024];
    
         memset(buffer, 0, sizeof(char));
    
         size_t numBytesEncrypted = 0;
   
         CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
                                                 
                                                                                            kCCOptionECBMode|kCCOptionPKCS7Padding,  //kCCOptionECBMode  kCCOptionPKCS7Padding
                                                 
                                                                                            [key UTF8String], kCCKeySizeDES,
                                                 
                                                                                            iv,
                                                 
                                                                                          textBytes, dataLength,
                                                 
                                                                                            buffer, 1024,
                                                 
                                                                                            &numBytesEncrypted);
            if (cryptStatus == kCCSuccess) {
        
                
                 NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
                //NSLog(@"ssf:%s",buffer);
                ciphertext = [ViewController base64Encoding:data];
               // NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
                //        Byte* bb = (Byte*)[data bytes];
                //        ciphertext = [self parseByteArray2HexString:bb];
        
             }
    
         return ciphertext;
   
     
}



 static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";


+(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;
}

 

2013-06-04 16:58:04 lusonglin121 阅读数 795
最近忙于android和iOS的项目,写完了android的DES 的ECB模式加密解密(相关连接:http://blog.csdn.net/vipa1888/article/details/8086037),又回到了Ios上面,因为本人也是最近今年开始研究ios的,所以Ios上面好多东西都不懂,进过了半年的研究,终于吧ios的DES 的ECB模式对称加密解密搞定了,本人遇到的问题很严重的问题,网上写的好多16进制数转化位字节都有问题的,经过本人研究发现他们有一个地方写错了,导致解密后的NSString 位null,我的代码已经修复了这个问题,下面贴出源代码供大家参考:


首先贴出加密类的头文件:

  1. //  
  2. //  DesUtil.h  
  3. //  Author:spring sky  
  4. //  QQ:840950105  
  5. //  Email:vipa1888@163.com  
  6. //  
  7.   
  8. #import <Foundation/Foundation.h>  
  9.   
  10. @interface DesUtil : NSObject  
  11. /**  
  12.  DES加密  
  13.  */  
  14. +(NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key;  
  15.   
  16. /**  
  17.  DES解密  
  18.  */  
  19. +(NSString *) decryptUseDES:(NSString *)plainText key:(NSString *)key;  
  20.   
  21.   
  22.   
  23. @end  

加密类的实现类:

  1. //  
  2. //  DesUtil.m  
  3. //  Author:spring sky  
  4. //  QQ:840950105  
  5. //  Email:vipa1888@163.com  
  6. //  
  7.   
  8. #import "DesUtil.h"  
  9. #import <CommonCrypto/CommonCryptor.h>  
  10. #import "ConverUtil.h"  
  11. @implementation DesUtil  
  12.   
  13.   
  14. static Byte iv[] = {1,2,3,4,5,6,7,8};  
  15. /*  
  16.  DES加密  
  17.  */  
  18. +(NSString *) encryptUseDES:(NSString *)clearText key:(NSString *)key  
  19. {  
  20.     NSString *ciphertext = nil;  
  21.     NSData *textData = [clearText dataUsingEncoding:NSUTF8StringEncoding];  
  22.     NSUInteger dataLength = [clearText length];  
  23.     unsigned char buffer[1024];  
  24.     memset(buffer, 0, sizeof(char));  
  25.     size_t numBytesEncrypted = 0;  
  26.       
  27.       
  28.     CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,  
  29.                                           kCCOptionECBMode,  
  30.                                           [key UTF8String], kCCKeySizeDES,  
  31.                                           iv,  
  32.                                           [textData bytes]  , dataLength,  
  33.                                           buffer, 1024,  
  34.                                           &numBytesEncrypted);  
  35.     if (cryptStatus == kCCSuccess) {  
  36.         NSLog(@"DES加密成功");  
  37.         NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];  
  38.         Byte* bb = (Byte*)[data bytes];  
  39.         ciphertext = [ConverUtil parseByteArray2HexString:bb];  
  40.     }else{  
  41.         NSLog(@"DES加密失败");  
  42.     }  
  43.     return ciphertext;  
  44. }  
  45.   
  46. /**  
  47.  DES解密  
  48.  */  
  49. +(NSString *) decryptUseDES:(NSString *)plainText key:(NSString *)key  
  50. {  
  51.     NSString *cleartext = nil;  
  52.     NSData *textData = [ConverUtil parseHexToByteArray:plainText];  
  53.     NSUInteger dataLength = [textData length];  
  54.     unsigned char buffer[1024];  
  55.     memset(buffer, 0, sizeof(char));  
  56.     size_t numBytesEncrypted = 0;  
  57.       
  58.       
  59.     CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,  
  60.                                           kCCOptionECBMode,  
  61.                                           [key UTF8String], kCCKeySizeDES,  
  62.                                           iv,  
  63.                                           [textData bytes]  , dataLength,  
  64.                                           buffer, 1024,  
  65.                                           &numBytesEncrypted);  
  66.     if (cryptStatus == kCCSuccess) {  
  67.         NSLog(@"DES解密成功");  
  68.   
  69.         NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];  
  70.         cleartext = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];  
  71.     }else{  
  72.         NSLog(@"DES解密失败");  
  73.     }  
  74.     return cleartext;  
  75. }  
  76.   
  77.   
  78.   
  79. @end  



下面是转码类,主要是16进制和字节的转化 
头文件:

  1. //  
  2. //  ConverUtil.h  
  3. //  Author:spring sky  
  4. //  QQ:840950105  
  5. //  Email:vipa1888@163.com  
  6. //  
  7.   
  8. #import <Foundation/Foundation.h>  
  9.   
  10. @interface ConverUtil : NSObject  
  11.   
  12. /**  
  13.  64编码  
  14.  */  
  15. +(NSString *)base64Encoding:(NSData*) text;  
  16.   
  17. /**  
  18.  字节转化为16进制数  
  19.  */  
  20. +(NSString *) parseByte2HexString:(Byte *) bytes;  
  21.   
  22. /**  
  23.  字节数组转化16进制数  
  24.  */  
  25. +(NSString *) parseByteArray2HexString:(Byte[]) bytes;  
  26.   
  27. /*  
  28.  将16进制数据转化成NSData 数组  
  29.  */  
  30. +(NSData*) parseHexToByteArray:(NSString*) hexString;  
  31.   
  32. @end  

实现类:

  1. //  
  2. //  ConverUtil.m  
  3. //  Author:spring sky  
  4. //  QQ:840950105  
  5. //  Email:vipa1888@163.com  
  6. //  
  7.   
  8. #import "ConverUtil.h"  
  9.   
  10. @implementation ConverUtil  
  11. static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";  
  12.   
  13. /**  
  14.  64编码  
  15.  */  
  16. +(NSString *)base64Encoding:(NSData*) text  
  17. {  
  18.     if (text.length == 0)  
  19.         return @"";  
  20.       
  21.     char *characters = malloc(text.length*3/2);  
  22.       
  23.     if (characters == NULL)  
  24.         return @"";  
  25.       
  26.     int end = text.length - 3;  
  27.     int index = 0;  
  28.     int charCount = 0;  
  29.     int n = 0;  
  30.       
  31.     while (index <= end) {  
  32.         int d = (((int)(((char *)[text bytes])[index]) & 0x0ff) << 16)  
  33.         | (((int)(((char *)[text bytes])[index + 1]) & 0x0ff) << 8)  
  34.         | ((int)(((char *)[text bytes])[index + 2]) & 0x0ff);  
  35.           
  36.         characters[charCount++] = encodingTable[(d >> 18) & 63];  
  37.         characters[charCount++] = encodingTable[(d >> 12) & 63];  
  38.         characters[charCount++] = encodingTable[(d >> 6) & 63];  
  39.         characters[charCount++] = encodingTable[d & 63];  
  40.           
  41.         index += 3;  
  42.           
  43.         if(n++ >= 14)  
  44.         {  
  45.             n = 0;  
  46.             characters[charCount++] = ' ';  
  47.         }  
  48.     }  
  49.       
  50.     if(index == text.length - 2)  
  51.     {  
  52.         int d = (((int)(((char *)[text bytes])[index]) & 0x0ff) << 16)  
  53.         | (((int)(((char *)[text bytes])[index + 1]) & 255) << 8);  
  54.         characters[charCount++] = encodingTable[(d >> 18) & 63];  
  55.         characters[charCount++] = encodingTable[(d >> 12) & 63];  
  56.         characters[charCount++] = encodingTable[(d >> 6) & 63];  
  57.         characters[charCount++] = '=';  
  58.     }  
  59.     else if(index == text.length - 1)  
  60.     {  
  61.         int d = ((int)(((char *)[text bytes])[index]) & 0x0ff) << 16;  
  62.         characters[charCount++] = encodingTable[(d >> 18) & 63];  
  63.         characters[charCount++] = encodingTable[(d >> 12) & 63];  
  64.         characters[charCount++] = '=';  
  65.         characters[charCount++] = '=';  
  66.     }  
  67.     NSString * rtnStr = [[NSString alloc] initWithBytesNoCopy:characters length:charCount encoding:NSUTF8StringEncoding freeWhenDone:YES];  
  68.     return rtnStr;  
  69. }  
  70.   
  71. /**  
  72.  字节转化为16进制数  
  73.  */  
  74. +(NSString *) parseByte2HexString:(Byte *) bytes  
  75. {  
  76.     NSMutableString *hexStr = [[NSMutableString alloc]init];  
  77.     int i = 0;  
  78.     if(bytes)  
  79.     {  
  80.         while (bytes[i] != '\0')  
  81.         {  
  82.             NSString *hexByte = [NSString stringWithFormat:@"%x",bytes[i] & 0xff];///16进制数  
  83.             if([hexByte length]==1)  
  84.                 [hexStr appendFormat:@"0%@", hexByte];  
  85.             else  
  86.                 [hexStr appendFormat:@"%@", hexByte];  
  87.               
  88.             i++;  
  89.         }  
  90.     }  
  91.     NSLog(@"bytes 的16进制数为:%@",hexStr);  
  92.     return hexStr;  
  93. }  
  94.   
  95.   
  96. /**  
  97.  字节数组转化16进制数  
  98.  */  
  99. +(NSString *) parseByteArray2HexString:(Byte[]) bytes  
  100. {  
  101.     NSMutableString *hexStr = [[NSMutableString alloc]init];  
  102.     int i = 0;  
  103.     if(bytes)  
  104.     {  
  105.         while (bytes[i] != '\0')  
  106.         {  
  107.             NSString *hexByte = [NSString stringWithFormat:@"%x",bytes[i] & 0xff];///16进制数  
  108.             if([hexByte length]==1)  
  109.                 [hexStr appendFormat:@"0%@", hexByte];  
  110.             else  
  111.                 [hexStr appendFormat:@"%@", hexByte];  
  112.               
  113.             i++;  
  114.         }  
  115.     }  
  116.     NSLog(@"bytes 的16进制数为:%@",hexStr);  
  117.     return [hexStr uppercaseString];  
  118. }  
  119.   
  120. /*  
  121.  将16进制数据转化成NSData 数组  
  122.  */  
  123. +(NSData*) parseHexToByteArray:(NSString*) hexString  
  124. {  
  125.     int j=0;  
  126.     Byte bytes[hexString.length];   
  127.     for(int i=0;i<[hexString length];i++)  
  128.     {  
  129.         int int_ch;  /// 两位16进制数转化后的10进制数  
  130.         unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)  
  131.         int int_ch1;  
  132.         if(hex_char1 >= '0' && hex_char1 <='9')  
  133.             int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48  
  134.         else if(hex_char1 >= 'A' && hex_char1 <='F')  
  135.             int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65  
  136.         else  
  137.             int_ch1 = (hex_char1-87)*16; //// a 的Ascll - 97  
  138.         i++;  
  139.         unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)  
  140.         int int_ch2;  
  141.         if(hex_char2 >= '0' && hex_char2 <='9')  
  142.             int_ch2 = (hex_char2-48); //// 0 的Ascll - 48  
  143.         else if(hex_char2 >= 'A' && hex_char1 <='F')  
  144.             int_ch2 = hex_char2-55; //// A 的Ascll - 65  
  145.         else  
  146.             int_ch2 = hex_char2-87; //// a 的Ascll - 97  
  147.           
  148.         int_ch = int_ch1+int_ch2;  
  149.         bytes[j] = int_ch;  ///将转化后的数放入Byte数组里  
  150.         j++;  
  151.     }  
  152.   
  153.     NSData *newData = [[NSData alloc] initWithBytes:bytes length:hexString.length/2];  
  154.     NSLog(@"newData=%@",newData);  
  155.     return newData;  
  156. }  
  157.   
  158. @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] bytes16进制数为: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



本人的工作内容主要是银行金融方面,所以经常会使用到各种的加密解密,如果有需要帮助的朋友可以联系我,如果我能搞定的,一定尽力而已!

欢迎转载,但是必须保留版权!

2014-01-06 11:45:50 yangtongwang123456 阅读数 572

最近忙于android和iOS的项目,写完了android的DES 的ECB模式加密解密(相关连接:http://blog.csdn.net/vipa1888/article/details/8086037),又回到了Ios上面,因为本人也是最近今年开始研究ios的,所以Ios上面好多东西都不懂,进过了半年的研究,终于吧ios的DES 的ECB模式对称加密解密搞定了,本人遇到的问题很严重的问题,网上写的好多16进制数转化位字节都有问题的,经过本人研究发现他们有一个地方写错了,导致解密后的NSString 位null,我的代码已经修复了这个问题,下面贴出源代码供大家参考:


首先贴出加密类的头文件:

  1. //  
  2. //  DesUtil.h  
  3. //  Author:spring sky  
  4. //  QQ:840950105  
  5. //  Email:vipa1888@163.com  
  6. //  
  7.   
  8. #import <Foundation/Foundation.h>  
  9.   
  10. @interface DesUtil : NSObject  
  11. /**  
  12.  DES加密  
  13.  */  
  14. +(NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key;  
  15.   
  16. /**  
  17.  DES解密  
  18.  */  
  19. +(NSString *) decryptUseDES:(NSString *)plainText key:(NSString *)key;  
  20.   
  21.   
  22.   
  23. @end  

加密类的实现类:

  1. //  
  2. //  DesUtil.m  
  3. //  Author:spring sky  
  4. //  QQ:840950105  
  5. //  Email:vipa1888@163.com  
  6. //  
  7.   
  8. #import "DesUtil.h"  
  9. #import <CommonCrypto/CommonCryptor.h>  
  10. #import "ConverUtil.h"  
  11. @implementation DesUtil  
  12.   
  13.   
  14. static Byte iv[] = {1,2,3,4,5,6,7,8};  
  15. /*  
  16.  DES加密  
  17.  */  
  18. +(NSString *) encryptUseDES:(NSString *)clearText key:(NSString *)key  
  19. {  
  20.     NSString *ciphertext = nil;  
  21.     NSData *textData = [clearText dataUsingEncoding:NSUTF8StringEncoding];  
  22.     NSUInteger dataLength = [clearText length];  
  23.     unsigned char buffer[1024];  
  24.     memset(buffer, 0, sizeof(char));  
  25.     size_t numBytesEncrypted = 0;  
  26.       
  27.       
  28.     CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,  
  29.                                           kCCOptionECBMode,  
  30.                                           [key UTF8String], kCCKeySizeDES,  
  31.                                           iv,  
  32.                                           [textData bytes]  , dataLength,  
  33.                                           buffer, 1024,  
  34.                                           &numBytesEncrypted);  
  35.     if (cryptStatus == kCCSuccess) {  
  36.         NSLog(@"DES加密成功");  
  37.         NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];  
  38.         Byte* bb = (Byte*)[data bytes];  
  39.         ciphertext = [ConverUtil parseByteArray2HexString:bb];  
  40.     }else{  
  41.         NSLog(@"DES加密失败");  
  42.     }  
  43.     return ciphertext;  
  44. }  
  45.   
  46. /**  
  47.  DES解密  
  48.  */  
  49. +(NSString *) decryptUseDES:(NSString *)plainText key:(NSString *)key  
  50. {  
  51.     NSString *cleartext = nil;  
  52.     NSData *textData = [ConverUtil parseHexToByteArray:plainText];  
  53.     NSUInteger dataLength = [textData length];  
  54.     unsigned char buffer[1024];  
  55.     memset(buffer, 0, sizeof(char));  
  56.     size_t numBytesEncrypted = 0;  
  57.       
  58.       
  59.     CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,  
  60.                                           kCCOptionECBMode,  
  61.                                           [key UTF8String], kCCKeySizeDES,  
  62.                                           iv,  
  63.                                           [textData bytes]  , dataLength,  
  64.                                           buffer, 1024,  
  65.                                           &numBytesEncrypted);  
  66.     if (cryptStatus == kCCSuccess) {  
  67.         NSLog(@"DES解密成功");  
  68.   
  69.         NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];  
  70.         cleartext = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];  
  71.     }else{  
  72.         NSLog(@"DES解密失败");  
  73.     }  
  74.     return cleartext;  
  75. }  
  76.   
  77.   
  78.   
  79. @end  



下面是转码类,主要是16进制和字节的转化 
头文件:

  1. //  
  2. //  ConverUtil.h  
  3. //  Author:spring sky  
  4. //  QQ:840950105  
  5. //  Email:vipa1888@163.com  
  6. //  
  7.   
  8. #import <Foundation/Foundation.h>  
  9.   
  10. @interface ConverUtil : NSObject  
  11.   
  12. /**  
  13.  64编码  
  14.  */  
  15. +(NSString *)base64Encoding:(NSData*) text;  
  16.   
  17. /**  
  18.  字节转化为16进制数  
  19.  */  
  20. +(NSString *) parseByte2HexString:(Byte *) bytes;  
  21.   
  22. /**  
  23.  字节数组转化16进制数  
  24.  */  
  25. +(NSString *) parseByteArray2HexString:(Byte[]) bytes;  
  26.   
  27. /*  
  28.  将16进制数据转化成NSData 数组  
  29.  */  
  30. +(NSData*) parseHexToByteArray:(NSString*) hexString;  
  31.   
  32. @end  

实现类:

  1. //  
  2. //  ConverUtil.m  
  3. //  Author:spring sky  
  4. //  QQ:840950105  
  5. //  Email:vipa1888@163.com  
  6. //  
  7.   
  8. #import "ConverUtil.h"  
  9.   
  10. @implementation ConverUtil  
  11. static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";  
  12.   
  13. /**  
  14.  64编码  
  15.  */  
  16. +(NSString *)base64Encoding:(NSData*) text  
  17. {  
  18.     if (text.length == 0)  
  19.         return @"";  
  20.       
  21.     char *characters = malloc(text.length*3/2);  
  22.       
  23.     if (characters == NULL)  
  24.         return @"";  
  25.       
  26.     int end = text.length - 3;  
  27.     int index = 0;  
  28.     int charCount = 0;  
  29.     int n = 0;  
  30.       
  31.     while (index <= end) {  
  32.         int d = (((int)(((char *)[text bytes])[index]) & 0x0ff) << 16)  
  33.         | (((int)(((char *)[text bytes])[index + 1]) & 0x0ff) << 8)  
  34.         | ((int)(((char *)[text bytes])[index + 2]) & 0x0ff);  
  35.           
  36.         characters[charCount++] = encodingTable[(d >> 18) & 63];  
  37.         characters[charCount++] = encodingTable[(d >> 12) & 63];  
  38.         characters[charCount++] = encodingTable[(d >> 6) & 63];  
  39.         characters[charCount++] = encodingTable[d & 63];  
  40.           
  41.         index += 3;  
  42.           
  43.         if(n++ >= 14)  
  44.         {  
  45.             n = 0;  
  46.             characters[charCount++] = ' ';  
  47.         }  
  48.     }  
  49.       
  50.     if(index == text.length - 2)  
  51.     {  
  52.         int d = (((int)(((char *)[text bytes])[index]) & 0x0ff) << 16)  
  53.         | (((int)(((char *)[text bytes])[index + 1]) & 255) << 8);  
  54.         characters[charCount++] = encodingTable[(d >> 18) & 63];  
  55.         characters[charCount++] = encodingTable[(d >> 12) & 63];  
  56.         characters[charCount++] = encodingTable[(d >> 6) & 63];  
  57.         characters[charCount++] = '=';  
  58.     }  
  59.     else if(index == text.length - 1)  
  60.     {  
  61.         int d = ((int)(((char *)[text bytes])[index]) & 0x0ff) << 16;  
  62.         characters[charCount++] = encodingTable[(d >> 18) & 63];  
  63.         characters[charCount++] = encodingTable[(d >> 12) & 63];  
  64.         characters[charCount++] = '=';  
  65.         characters[charCount++] = '=';  
  66.     }  
  67.     NSString * rtnStr = [[NSString alloc] initWithBytesNoCopy:characters length:charCount encoding:NSUTF8StringEncoding freeWhenDone:YES];  
  68.     return rtnStr;  
  69. }  
  70.   
  71. /**  
  72.  字节转化为16进制数  
  73.  */  
  74. +(NSString *) parseByte2HexString:(Byte *) bytes  
  75. {  
  76.     NSMutableString *hexStr = [[NSMutableString alloc]init];  
  77.     int i = 0;  
  78.     if(bytes)  
  79.     {  
  80.         while (bytes[i] != '\0')  
  81.         {  
  82.             NSString *hexByte = [NSString stringWithFormat:@"%x",bytes[i] & 0xff];///16进制数  
  83.             if([hexByte length]==1)  
  84.                 [hexStr appendFormat:@"0%@", hexByte];  
  85.             else  
  86.                 [hexStr appendFormat:@"%@", hexByte];  
  87.               
  88.             i++;  
  89.         }  
  90.     }  
  91.     NSLog(@"bytes 的16进制数为:%@",hexStr);  
  92.     return hexStr;  
  93. }  
  94.   
  95.   
  96. /**  
  97.  字节数组转化16进制数  
  98.  */  
  99. +(NSString *) parseByteArray2HexString:(Byte[]) bytes  
  100. {  
  101.     NSMutableString *hexStr = [[NSMutableString alloc]init];  
  102.     int i = 0;  
  103.     if(bytes)  
  104.     {  
  105.         while (bytes[i] != '\0')  
  106.         {  
  107.             NSString *hexByte = [NSString stringWithFormat:@"%x",bytes[i] & 0xff];///16进制数  
  108.             if([hexByte length]==1)  
  109.                 [hexStr appendFormat:@"0%@", hexByte];  
  110.             else  
  111.                 [hexStr appendFormat:@"%@", hexByte];  
  112.               
  113.             i++;  
  114.         }  
  115.     }  
  116.     NSLog(@"bytes 的16进制数为:%@",hexStr);  
  117.     return [hexStr uppercaseString];  
  118. }  
  119.   
  120. /*  
  121.  将16进制数据转化成NSData 数组  
  122.  */  
  123. +(NSData*) parseHexToByteArray:(NSString*) hexString  
  124. {  
  125.     int j=0;  
  126.     Byte bytes[hexString.length];   
  127.     for(int i=0;i<[hexString length];i++)  
  128.     {  
  129.         int int_ch;  /// 两位16进制数转化后的10进制数  
  130.         unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)  
  131.         int int_ch1;  
  132.         if(hex_char1 >= '0' && hex_char1 <='9')  
  133.             int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48  
  134.         else if(hex_char1 >= 'A' && hex_char1 <='F')  
  135.             int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65  
  136.         else  
  137.             int_ch1 = (hex_char1-87)*16; //// a 的Ascll - 97  
  138.         i++;  
  139.         unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)  
  140.         int int_ch2;  
  141.         if(hex_char2 >= '0' && hex_char2 <='9')  
  142.             int_ch2 = (hex_char2-48); //// 0 的Ascll - 48  
  143.         else if(hex_char2 >= 'A' && hex_char1 <='F')  
  144.             int_ch2 = hex_char2-55; //// A 的Ascll - 65  
  145.         else  
  146.             int_ch2 = hex_char2-87; //// a 的Ascll - 97  
  147.           
  148.         int_ch = int_ch1+int_ch2;  
  149.         bytes[j] = int_ch;  ///将转化后的数放入Byte数组里  
  150.         j++;  
  151.     }  
  152.   
  153.     NSData *newData = [[NSData alloc] initWithBytes:bytes length:hexString.length/2];  
  154.     NSLog(@"newData=%@",newData);  
  155.     return newData;  
  156. }  
  157.   
  158. @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

2012-10-18 19:57:47 vipa1888 阅读数 8838
    最近忙于android和iOS的项目,写完了android的DES 的ECB模式加密解密(相关连接:http://blog.csdn.net/vipa1888/article/details/8086037),又回到了Ios上面,因为本人也是最近今年开始研究ios的,所以Ios上面好多东西都不懂,进过了半年的研究,终于吧ios的DES 的ECB模式对称加密解密搞定了,本人遇到的问题很严重的问题,网上写的好多16进制数转化位字节都有问题的,经过本人研究发现他们有一个地方写错了,导致解密后的NSString 位null,我的代码已经修复了这个问题,下面贴出源代码供大家参考:


首先贴出加密类的头文件:

//
//  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 DesUtil


static 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 ConverUtil
static 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



本人的工作内容主要是银行金融方面,所以经常会使用到各种的加密解密,如果有需要帮助的朋友可以联系我,如果我能搞定的,一定尽力而已!

欢迎转载,但是必须保留版权!







2015-07-22 17:14:18 muzhenhua 阅读数 2086

先了解下 DES ECB模式

ECB模式:
优点:
1. 简单;
2. 有利于并行计算;
3. 误差不会被传递;
缺点:
1. 不能隐藏明文的模式;
2. 可能对明文进行主动攻击;

DES ECB(电子密本方式)其实非常简单,就是将数据按照8个字节一段进行DES加密或解密得到一段段的8个字节的密文或者明文,最后一段不足8个字节(一般补0或者F),按照需求补足8个字节进行计算(并行计算),之后按照顺序将计算所得的数据连在一起即可,各段数据之间互不影响。

CBC模式:
优点:
1. 不容易主动攻击,安全性好于ECB,是SSL、IPSec的标准;
缺点:
1. 不利于并行计算;
2. 误差传递;
3. 需要初始化向量IV;

DES CBC(密文分组链接方式)有点麻烦,它的实现机制使加密的各段数据之间有了联系。其实现的机理如下:
加密步骤如下:
1. 首先将数据按照8个字节一组进行分组得到D1D2......Dn(若数据不是8的整数倍,用指定的PADDING数据补位)
2. 第一组数据D1与初始化向量I异或后的结果进行DES加密得到第一组密文C1(初始化向量I为全零)
3. 第二组数据D2与第一组的加密结果C1异或以后的结果进行DES加密,得到第二组密文C2
4. 之后的数据以此类推,得到Cn
5. 按顺序连为C1C2C3......Cn即为加密结果。

首先贴出加密类的头文件:

#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonCryptor.h>
#import "ConverUtil.h"
#import "Constants.h"

@interface DES : NSObject
//加密
- (NSString *) encryptUseDES:(NSString *)plainText key:(NSString*)key;
//解密
-(NSString*) decryptUseDES:(NSString*)cipherText key:(NSString*)key;

@end

加密类的实现类:

#import "DES.h"

@implementation DES
//DES_IV 自己定义的一个字符串 八个字节 一定要是八个字节
-(Byte *) getIv{
    
    NSString *testString = DES_IV;
    NSData *testData = [testString dataUsingEncoding: NSUTF8StringEncoding];
    //    for(int i=0;i<[testData length];i++)
    //        printf("testByte = %d\n",testByte[i]);
    return (Byte *)[testData bytes];
}
//plainText需加密 字符串 key 定义好的 加密 解密 钥匙
- (NSString *) encryptUseDES:(NSString *)plainText key:(NSString*)key{
    
    Byte *iv=[self getIv];
    
//    NSString *escape=[plainText stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
//    return escape;
    
    NSData* data=[plainText dataUsingEncoding: NSUTF8StringEncoding];
    
    NSUInteger bufferSize=([data length] + kCCKeySizeDES) & ~(kCCKeySizeDES -1);
    
    char buffer[bufferSize];
    
    memset(buffer, 0,sizeof(buffer));
    
    size_t bufferNumBytes;
    
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          
                                          kCCAlgorithmDES,
                                          
                                          kCCOptionPKCS7Padding,
                                          
                                          [key UTF8String],
                                          
                                          kCCKeySizeDES,
                                          
                                          iv   ,
                                          
                                          [data bytes],
                                          
                                          [data length],
                                          
                                          buffer,
                                          
                                          bufferSize,
                                          
                                          &bufferNumBytes);
    
    if (cryptStatus ==kCCSuccess) {
        
        NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)bufferNumBytes];
        
        return [ConverUtil parseByteArray2HexString:[data bytes] count:bufferNumBytes] ;
        //        NSLog(@"objccipherTextBytes:%@",[XYDES dataToHex:data]);
        //        ciphertext = [GTMBase64 stringByEncodingData:data];
        //        NSLog(@"objccipherTextBase64:%@",ciphertext);
    }
    
    return nil;
}

-(NSString*) decryptUseDES:(NSString*)cipherText key:(NSString*)key{
    
    Byte *iv=[self getIv];
    
    NSData* data = [ConverUtil parseHexToByteArray:cipherText];
    
    NSUInteger bufferSize=([data length] + kCCKeySizeDES) & ~(kCCKeySizeDES -1);
    
    char buffer[bufferSize];
    
    memset(buffer, 0,sizeof(buffer));
    
    size_t bufferNumBytes;
    
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          
                                          kCCAlgorithmDES,
                                          
                                          kCCOptionPKCS7Padding,
                                          
                                          [key UTF8String],
                                          
                                          kCCKeySizeDES,
                                          
                                          iv,
                                          
                                          [data bytes],
                                          
                                          [data length],
                                          
                                          buffer,
                                          
                                          bufferSize,
                                          
                                          &bufferNumBytes);
    
    NSString* plainText = nil;
    
    if (cryptStatus ==kCCSuccess) {
        
        NSData *plainData =[NSData dataWithBytes:buffer length:(NSUInteger)bufferNumBytes];
        
        plainText = [[NSString alloc] initWithData:plainData encoding:NSUTF8StringEncoding];
    }
    
    return plainText;
}

@end

下面是转码类,主要是16进制和字节的转化 
头文件:
#import <Foundation/Foundation.h>

@interface ConverUtil : NSObject

/**
 64编码
 */
+(NSString *)base64Encoding:(NSData*) text;

/**
 字节转化为16进制数
 */
+(NSString *) parseByte2HexString:(Byte *) bytes;

/**
 字节数组转化16进制数
 */
+(NSString *) parseByteArray2HexString:(Byte[]) bytes count:(int)count;

/*
 将16进制数据转化成NSData 数组
 */
+(NSData*) parseHexToByteArray:(NSString*) hexString;

@end

实现类:

#import "ConverUtil.h"

@implementation ConverUtil
static 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++;
        }
    }
    
    return hexStr;
}


/**
 字节数组转化16进制数
 */
+(NSString *) parseByteArray2HexString:(Byte[]) bytes count:(int)count
{
    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++;
        //        }
        for (int i=0;i< count;i++)
        {
            NSString *hexByte = [NSString stringWithFormat:@"%x",bytes[i] & 0xff];///16进制数
            
            if([hexByte length]==1)
                [hexStr appendFormat:@"0%@", hexByte];
            else
                [hexStr appendFormat:@"%@", hexByte];
            
            //            i++;
        }
    }
    
    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];
    
    return newData;
}

@end



ios16进制加密AES128ECBPKCS7Padding

博文 来自: L_weiguo
没有更多推荐了,返回首页