這裏是AES的方式,可能是DES有異曲同工之處,看看這個作品跟我... 創建一個新的類別AES
上NSData
對於的NSData + AES.h
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonCryptor.h>
@interface NSData (AES)
- (NSData*) EncryptAES: (NSString *) key;
- (NSData *) DecryptAES: (NSString *) key;
@end
對於NSData的+ AES.m
#import "NSData+AES.h"
@implementation NSData(AES)
- (NSData*) EncryptAES: (NSString *) key
{
char keyPtr[kCCKeySizeAES256+1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString: keyPtr maxLength: sizeof(keyPtr) encoding: NSUTF16StringEncoding];
size_t numBytesEncrypted = 0;
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
CCCryptorStatus result = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL,
[self bytes], [self length],
buffer, bufferSize,
&numBytesEncrypted);
if(result == kCCSuccess)
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
return nil;
}
- (NSData *) DecryptAES: (NSString *) key
{
char keyPtr[kCCKeySizeAES256+1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString: keyPtr maxLength: sizeof(keyPtr) encoding: NSUTF16StringEncoding];
size_t numBytesEncrypted = 0;
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer_decrypt = malloc(bufferSize);
CCCryptorStatus result = CCCrypt(kCCDecrypt , kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL,
[self bytes], [self length],
buffer_decrypt, bufferSize,
&numBytesEncrypted);
if(result == kCCSuccess)
return [NSData dataWithBytesNoCopy:buffer_decrypt length:numBytesEncrypted];
return nil;
}
@end
用法: 導入的NSData + AES.h
//Encryption
NSString *myString = @"This is the content";
NSString *key = @"my secret key";
NSData *data = [myString dataUsingEncoding:NSUTF8StringEncoding];
NSData *encryptedData = [data EncryptAES:key];
//Decryption
NSString *decryptedString = [[[NSString alloc] initWithData:[encryptedData DecryptAES:key] encoding:NSUTF8StringEncoding] autorelease]; // remove autorelease if using ARC
以及你如何解密? – Hlung