在PHP中,我有以下代码:
$key = 'HelloKey';
$data = 'This is a secret';
$mdKey = $key;
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $mdKey, $data, MCRYPT_MODE_CBC));
echo $encrypted;
它打印:IRIl6K1tAUSwEBNmPXxnzgVobvTfCxwvQJGQmnf63UU=
编辑:我已修改我的代码以不使用零填充:
$key = 'HelloKey';
$data = 'This is a secret';
$mdKey = $key;
$block = mcrypt_get_block_size (MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$pad = $block - (strlen($data) % $block);
$data .= str_repeat(chr($pad), $pad);
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $mdKey, $data, MCRYPT_MODE_CBC));
echo $encrypted;
它现在打印:q2THgtCcd+r5kQV/W6gsU56dtfx+IEWPNc2MsjcHCNw=
在iOS中,我有以下代码:
NSString *key = @"HelloKey";
NSString *mdKey = key;
NSString *data = @"This is a secret";
NSData *plain = [data dataUsingEncoding:NSUTF8StringEncoding];
NSData *cipher = [SCEncryptionAES AES256EncryptData:plain withKey:mdKey];
NSLog(@"%@", [SCBase64 base64Encode:cipher length:cipher.length]);
它打印:f8pFZU7kdJNOriA0EBzFfTHsJFOG1MzCw7xV8ztLYQw=
这是我的AES256EncryptData: withKey
方法:
+ (NSData *)AES256EncryptData:(NSData *)data withKey:(NSString *)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = data.length;
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
data.bytes, dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer); //free the buffer;
return nil;
}
我没有使用初始化向量或 md5-key 散列,这可能会使这个相当简单的示例过于复杂。此外,我确保 base64 函数的工作方式相同,因此错误无疑是在AES256EncryptData: withKey
- 方法中。到目前为止,我只看到了这个实现(我冒昧地采用了)。有什么我做错了吗?