
使用方法 先导入头文件 #import "NSData+AES.h"
//AES测试
//用来密钥
NSString *key = @"";
//用来发送的原始数据
NSString *secret = @"I Love You";
//数据转码
NSData *plain = [secret dataUsingEncoding:NSUTF8StringEncoding];
//用密钥加密
NSData *cipher = [plain AES256EncryptWithKey:key]; //输出测试
NSLog(@"%@",[cipher newStringInBase64FromData]);
printf("%s\n", [[cipher description] UTF8String]);
//打印出null,这是因为没有解密
NSLog(@"%@", [[NSString alloc] initWithData:cipher encoding:NSUTF8StringEncoding]); //解密方法
plain = [cipher AES256DecryptWithKey:key];
printf("%s\n", [[plain description] UTF8String]);
NSLog(@"%@", [[NSString alloc] initWithData:plain encoding:NSUTF8StringEncoding]);
自建NSData类别 命名AES
NSData+AES.h
#import <Foundation/Foundation.h> @interface NSData (AES) - (NSData *)AES256EncryptWithKey:(NSString *)key; //加密 - (NSData *)AES256DecryptWithKey:(NSString *)key; //解密 - (NSString *)newStringInBase64FromData; //追加64编码 + (NSString*)base64encode:(NSString*)str; //同上64编码 @end
NSData+AES.m
#import "NSData+AES.h"
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonCryptor.h> static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; @implementation NSData (AES) - (NSData *)AES256EncryptWithKey:(NSString *)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding) // fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]; NSUInteger dataLength = [self length]; //See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize); size_t numBytesEncrypted = ;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
} free(buffer); //free the buffer;
return nil;
} - (NSData *)AES256DecryptWithKey:(NSString *)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding) // fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]; NSUInteger dataLength = [self length]; //See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize); size_t numBytesDecrypted = ;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesDecrypted); if (cryptStatus == kCCSuccess) {
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
} free(buffer); //free the buffer;
return nil;
} - (NSString *)newStringInBase64FromData //追加64编码
{
NSMutableString *dest = [[NSMutableString alloc] initWithString:@""];
unsigned char * working = (unsigned char *)[self bytes];
int srcLen = [self length];
for (int i=; i<srcLen; i += ) {
for (int nib=; nib<; nib++) {
int byt = (nib == )?:nib-;
int ix = (nib+)*;
if (i+byt >= srcLen) break;
unsigned char curr = ((working[i+byt] << (-ix)) & 0x3F);
if (i+nib < srcLen) curr |= ((working[i+nib] >> ix) & 0x3F);
[dest appendFormat:@"%c", base64[curr]];
}
}
return dest;
} + (NSString*)base64encode:(NSString*)str
{
if ([str length] == )
return @"";
const char *source = [str UTF8String];
int strlength = strlen(source);
char *characters = malloc(((strlength + ) / ) * );
if (characters == NULL)
return nil;
NSUInteger length = ;
NSUInteger i = ;
while (i < strlength) {
char buffer[] = {,,};
short bufferLength = ;
while (bufferLength < && i < strlength)
buffer[bufferLength++] = source[i++];
characters[length++] = base64[(buffer[] & 0xFC) >> ];
characters[length++] = base64[((buffer[] & 0x03) << ) | ((buffer[] & 0xF0) >> )];
if (bufferLength > )
characters[length++] = base64[((buffer[] & 0x0F) << ) | ((buffer[] & 0xC0) >> )];
else characters[length++] = '=';
if (bufferLength > )
characters[length++] = base64[buffer[] & 0x3F];
else characters[length++] = '=';
}
NSString *g = [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES];
return g;
} @end