我可以加密数据但不能解密

时间:2019-02-11 09:39:50

标签: php security encryption aes

我可以成功加密传递的数据,但遗憾的是无法解密。我的decrypt()函数有什么问题?也许与我的Initialization Vector(iv)有关。这是我的代码:

function pad($data, $size) {
    $length = $size - strlen($data) % $size;
    return $data . str_repeat(chr($length), $length);
}

function unpad($data) {
    return substr($data, 0, -ord($data[strlen($data) - 1]));
}

//CORRECT ENCRYPTION METHOD
function encrypt($data) {
    $key = "SiadajerSiadajer";
    $iv_size = 16; 
    $iv = openssl_random_pseudo_bytes($iv_size, $strong);
    $encryptedData = openssl_encrypt(pad($data, 16), 'AES-256-CBC', $key,   OPENSSL_RAW_DATA, $iv);
    $joinedData = hex2bin(bin2hex($iv).bin2hex($encryptedData));
    $encodedJoinedData = base64_encode($joinedData);
    return $encodedJoinedData; 
}

//WRONG DECRYPTION FUNCTION
function decrypt($encodedJoinedData){
    $key = "SiadajerSiadajer";
    $DecodedData = base64_decode($encodedJoinedData);
    $size = strlen($DecodedData);
    $cipheredsize = $size - 16;
    $iv = substr($DecodedData, 0, 16);
    $halfDecryptedData = substr($DecodedData, 16, $size);
    $decryptedData = openssl_decrypt(unpad($halfDecryptedData, 16), 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    return $decryptedData;
}

$test = encrypt("sssss");
print $test;
$test2 = decrypt($test);
print $test2;

1 个答案:

答案 0 :(得分:1)

encrypt方法中,替换行

$joinedData = hex2bin(bin2hex($iv).bin2hex($encryptedData));

使用

$joinedData = $iv.$encryptedData;

因为不需要上一个表达式中的转换。这种替换不会改变结果。

解密部分的可能解决方案可能是:

function decrypt($encodedJoinedData) {
    $joinedData = base64_decode($encodedJoinedData);                        
    $iv = substr($joinedData, 0, 16);
    $encryptedData = substr($joinedData, 16);
    $key = "SiadajerSiadajer";
    $decryptedData = openssl_decrypt($encryptedData, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);   
    $unpaddedData = unpad($decryptedData);                              
    return $unpaddedData;
}