0
我目前正在iOS中進行加密並在PHP中進行解密。如果我正在加密/解密的字符串的長度小於16個字符,它工作正常。功能mcrypt_decrypt()僅適用於短字符串
iOS的代碼進行加密:
- (NSData *)AES128Encrypt:(NSData *)this
{
// ‘key’ should be 16 bytes for AES128
char keyPtr[kCCKeySizeAES128 + 1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
NSString *key = @"123456789";
// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [this 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, kCCOptionECBMode | kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES128,
NULL /* initialization vector (optional) */,
[this 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;
}
PHP代碼解密:
function decryptThis($key, $pass)
{
$base64encoded_ciphertext = $pass;
$res_non = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $base64encoded_ciphertext, MCRYPT_MODE_CBC);
$decrypted = $res_non;
$dec_s2 = strlen($decrypted);
$padding = ord($decrypted[$dec_s2-1]);
$decrypted = substr($decrypted, 0, -$padding);
return $decrypted;
}
如果解密字符串的長度超過16個字符PHP只返回@ 「\ n \ n」更長。但是,像'什麼'短字符串被正確解密,並且PHP返回@「what \ n \ n」。這裏發生了什麼?我希望能夠解密超過500個字符的字符串。
在iOS中,CCCrypt函數只接受2個選項:kCCOptionECBMode和kCCOptionPKCS7Padding。刪除ECB選項顯然會在CBC中加密它。我想使用CBC,因爲我讀它會保存更長的字符串。 – GabCas 2013-03-19 17:55:05
@GabCas CBC模式*應該*用於字符串,因爲ECB模式不適用於字符串。兩者都可以容納無限數量的數據(可能受限於底層分組密碼的安全考慮)。 CBC的安全使用需要一個隨機的IV,它可以用密文發送。 – 2013-03-19 19:35:16