- (NSData *)AES256EncryptWithKey:(NSString *)key {
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
NSMutableData *data = [[NSData randomDataWithLength:AES_256_IV_SIZE] mutableCopy]; //IV
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
[key cStringUsingEncoding:NSUTF8StringEncoding],
[key length],
[data bytes],
[self bytes],
dataLength,
buffer,
bufferSize,
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
NSData *message = [NSData dataWithBytes:buffer
length:numBytesEncrypted]; //Message
/* Do HMac */
NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
NSData *hmac = [message doHmacWithKeyData:keyData];
/* IV+Message+HMac */
[data appendData:message];
[data appendData:hmac];
free(buffer);
return data;
}
free(buffer);
return nil;
}
- (NSData *)doHmacWithKeyData:(NSData *)salt {
NSMutableData *macOut = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA256,
salt.bytes,
salt.length,
self.bytes,
self.length,
macOut.mutableBytes);
return macOut;
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.