【发布时间】:2014-12-21 23:48:27
【问题描述】:
我目前正在从事一个需要我解密数据的项目。我有一个可用的 php 版本,并希望将其移植到我的 iOS 项目中。
这是工作的 php 函数:
public function decryptCBC($data, $key, $iv) {
// Decode the key and IV.
$iv = base64_decode($iv);
$key = base64_decode($key);
// Decrypt the data.
$data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
$padding = ord($data[strlen($data) - 1]);
return substr($data, 0, -$padding);
}
在 Objective C 中,这是我尝试过的,但还没有成功
- (NSData *) decryptCBC:(NSData*)data WithKey:(NSString *)key andIv:(NSString *)iv {
NSData *keyData = [[NSData alloc] initWithBase64EncodedString:key options:0];
NSData *ivData = [[NSData alloc] initWithBase64EncodedString:iv options:0];
key = [[NSString alloc] initWithData:keyData encoding:NSASCIIStringEncoding];
char keyPtr[kCCKeySizeAES128+1];
bzero(keyPtr, sizeof(keyPtr)); // fill with 0s - padding
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = data.length;
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, 0 ,
keyPtr, kCCKeySizeAES128,
[ivData bytes],
[data bytes], dataLength,
buffer, bufferSize,
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
//the returned NSData takes ownership of the buffer and will free it on deallocation
NSData *response = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted-1];
return response;
}
free(buffer); //free the buffer;
return nil;
}
如果有人知道我做错了什么,我将不胜感激。
谢谢 /乔纳森
【问题讨论】:
-
提供密钥、iv 和数据进出两个函数的十六进制转储。有一些关于填充的问题。
标签: php objective-c encryption base64 aes