这是 AES 的一种方式,可能对于 DES 来说是类似的,看看这对我有用...AES
在NSData
For 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