[iOS]AES加密在iOS上面的实现

[iOS]AES加密在iOS上面的实现 

Encryption.h文件

[plain] view plain copy
  1. //  
  2. //  Encryption.h  
  3. //  DownloadFile  
  4. //  
  5. //  Created by zhoumin on 12-1-16.  
  6. //  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.  
  7. //  
  8.   
  9. #import <Foundation/Foundation.h>  
  10.   
  11. @class NSString;  
  12.   
  13. @interface NSData (Encryption)  
  14.   
  15. - (NSData *)AES256EncryptWithKey:(NSString *)key;   //加密  
  16. - (NSData *)AES256DecryptWithKey:(NSString *)key;   //解密  
  17. - (NSString *)newStringInBase64FromData;            //追加64编码  
  18. + (NSString*)base64encode:(NSString*)str;           //同上64编码  
  19.   
  20. @end  

Encryption.m文件

[plain] view plain copy
  1. //  
  2. //  Encryption.m  
  3. //  DownloadFile  
  4. //  
  5. //  Created by  on 12-1-16.  
  6. //  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.  
  7. //  
  8.   
  9. #import "Encryption.h"  
  10. #import <CommonCrypto/CommonCryptor.h>  
  11.   
  12.   
  13. static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";  
  14.   
  15. @implementation NSData (Encryption)  
  16.   
  17. - (NSData *)AES256EncryptWithKey:(NSString *)key   //加密  
  18. {  
  19.     char keyPtr[kCCKeySizeAES256+1];  
  20.     bzero(keyPtr, sizeof(keyPtr));  
  21.     [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];  
  22.     NSUInteger dataLength = [self length];  
  23.     size_t bufferSize = dataLength + kCCBlockSizeAES128;  
  24.     void *buffer = malloc(bufferSize);  
  25.     size_t numBytesEncrypted = 0;  
  26.     CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,  
  27.                                           kCCOptionPKCS7Padding | kCCOptionECBMode,  
  28.                                           keyPtr, kCCBlockSizeAES128,  
  29.                                           NULL,  
  30.                                           [self bytes], dataLength,  
  31.                                           buffer, bufferSize,  
  32.                                           &numBytesEncrypted);  
  33.     if (cryptStatus == kCCSuccess) {  
  34.         return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];  
  35.     }  
  36.     free(buffer);  
  37.     return nil;  
  38. }  
  39.   
  40.   
  41. - (NSData *)AES256DecryptWithKey:(NSString *)key   //解密  
  42. {  
  43.     char keyPtr[kCCKeySizeAES256+1];  
  44.     bzero(keyPtr, sizeof(keyPtr));  
  45.     [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];  
  46.     NSUInteger dataLength = [self length];  
  47.     size_t bufferSize = dataLength + kCCBlockSizeAES128;  
  48.     void *buffer = malloc(bufferSize);  
  49.     size_t numBytesDecrypted = 0;  
  50.     CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,  
  51.                                           kCCOptionPKCS7Padding | kCCOptionECBMode,  
  52.                                           keyPtr, kCCBlockSizeAES128,  
  53.                                           NULL,  
  54.                                           [self bytes], dataLength,  
  55.                                           buffer, bufferSize,  
  56.                                           &numBytesDecrypted);  
  57.     if (cryptStatus == kCCSuccess) {  
  58.         return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];  
  59.     }  
  60.     free(buffer);  
  61.     return nil;  
  62. }  
  63.   
  64.   
  65. - (NSString *)newStringInBase64FromData            //追加64编码  
  66. {  
  67.     NSMutableString *dest = [[NSMutableString alloc] initWithString:@""];  
  68.     unsigned char * working = (unsigned char *)[self bytes];  
  69.     int srcLen = [self length];  
  70.     for (int i=0; i<srcLen; i += 3) {  
  71.         for (int nib=0; nib<4; nib++) {  
  72.             int byt = (nib == 0)?0:nib-1;  
  73.             int ix = (nib+1)*2;  
  74.             if (i+byt >= srcLen) break;  
  75.             unsigned char curr = ((working[i+byt] << (8-ix)) & 0x3F);  
  76.             if (i+nib < srcLen) curr |= ((working[i+nib] >> ix) & 0x3F);  
  77.             [dest appendFormat:@"%c", base64[curr]];  
  78.         }  
  79.     }  
  80.     return dest;  
  81. }  
  82.   
  83. + (NSString*)base64encode:(NSString*)str  
  84. {  
  85.     if ([str length] == 0)  
  86.         return @"";  
  87.     const char *source = [str UTF8String];  
  88.     int strlength  = strlen(source);  
  89.     char *characters = malloc(((strlength + 2) / 3) * 4);  
  90.     if (characters == NULL)  
  91.         return nil;  
  92.     NSUInteger length = 0;  
  93.     NSUInteger i = 0;  
  94.     while (i < strlength) {  
  95.         char buffer[3] = {0,0,0};  
  96.         short bufferLength = 0;  
  97.         while (bufferLength < 3 && i < strlength)  
  98.             buffer[bufferLength++] = source[i++];  
  99.         characters[length++] = base64[(buffer[0] & 0xFC) >> 2];  
  100.         characters[length++] = base64[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];  
  101.         if (bufferLength > 1)  
  102.             characters[length++] = base64[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];  
  103.         else characters[length++] = '=';  
  104.         if (bufferLength > 2)  
  105.             characters[length++] = base64[buffer[2] & 0x3F];  
  106.         else characters[length++] = '=';  
  107.     }  
  108.     NSString *g = [[[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES] autorelease];  
  109.     return g;  
  110. }  
  111.   
  112.   
  113. @end  

测试
  1. NSString *key = @"my password";    
  2. NSString *secret = @"text to encrypt";    
  3. //加密    
  4. NSData *plain = [secret dataUsingEncoding:NSUTF8StringEncoding];    
  5. NSData *cipher = [plain AES256EncryptWithKey:key];    
  6. NSLog(@"%@",[[cipher newStringInBase64FromData] autorelease]);    
  7. printf("%s\n", [[cipher description] UTF8String]);    
  8. NSLog(@"%@", [[[NSString alloc] initWithData:cipher encoding:NSUTF8StringEncoding] autorelease]);//打印出null,这是因为没有解密。    
  9. //解密    
  10. plain = [cipher AES256DecryptWithKey:key];    
  11. printf("%s\n", [[plain description] UTF8String]);    
  12. NSLog(@"%@", [[[NSString alloc] initWithData:plain encoding:NSUTF8StringEncoding] autorelease]);    
  13. //打印出secret的内容,用密码解密过了。如果使用错误的密码,则打印null    


demo下载:http://download.csdn.net/detail/z251257144/4820200
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值