1、NSData的MD5加密
#define CC_MD5_DIGEST_LENGTH 16
//计算NSData 的MD5值
+ (NSString*)getMD5WithData:(NSData *)data{
//需要MD5变量并且初始化
CC_MD5_CTX md5;
CC_MD5_Init(&md5);
//开始加密(第一个参数:对md5变量去地址,要为该变量指向的内存空间计算好数据,第二个参数:需要计算的源数据,第三个参数:源数据的长度)
CC_MD5_Update(&md5, data.bytes, (CC_LONG)data.length);
//声明一个无符号的字符数组,用来盛放转换好的数据
unsigned char result[CC_MD5_DIGEST_LENGTH];
//将数据放入result数组
CC_MD5_Final(result, &md5);
//将result中的字符拼接为OC语言中的字符串,以便我们使用。
NSMutableString *resultString = [NSMutableString string];
for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
[resultString appendFormat:@"%02X",result[i]];
}
return resultString;
}
2、NSData的AES256加密、解密
- (NSData *)aes256_encrypt:(NSString *)key //加密
{
char keyPtr[kCCKeySizeAES256+1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,
kCCOptionPKCS7Padding | kCCOptionECBMode,
keyPtr, kCCBlockSizeAES128,
NULL,
[self bytes], dataLength,
buffer, bufferSize,
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer);
return nil;
}
- (NSData *)aes256_decrypt:(NSString *)key //解密
{
char keyPtr[kCCKeySizeAES256+1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,
kCCOptionPKCS7Padding | kCCOptionECBMode,
keyPtr, kCCBlockSizeAES128,
NULL,
[self bytes], dataLength,
buffer, bufferSize,
&numBytesDecrypted);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}
free(buffer);
return nil;
}