在将一些 JSON 数据插入 SQL 数据库之前,我使用 openssl_encrypt 对其进行加密。
$cypherMethod = 'AES-256-CBC';
$key = 'WHATEVER';
// Then we generate a random Initialization Vector - which is stored with record in DB
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cypherMethod));
// Now we run the encryption process and convert output to Base64 to make DB storage easier
$userdata = openssl_encrypt($userdata, $cypherMethod, $key, $options=0, $iv);
$userdata = base64_encode($userdata);
这工作正常,然后将数据添加到数据库中。
然后在我解密的另一端:
$cypherMethod = 'AES-256-CBC';
$key = 'WHATEVER';
$iv = 'GRABBED FROM DB RECORD';
$userdata = base64_decode($userdata);
$userdata = openssl_decrypt($userdata, $cypherMethod, $key, $options=0, $iv);
现在,解密过程工作正常,但 JSON 数据以转义斜线结束,然后我必须使用 stripslashes() 将其删除。
这不是一个大问题,但为什么会出现斜线?我知道 Base64 添加了斜杠,但我只是在初始加密后进行 base64 编码,所以我无法理解斜杠是如何进入底层 JSON 数据的?
答案 0 :(得分:0)
@CBroe 的评论应该会将您引导到正确的位置进行搜索。下面您会发现您的代码附加了一些 JSON 数据,以证明 OpenSSL 在加密或解密期间不会更改数据。
输出将是:
userdata before encryption: {name: "John", age: 31, city: "New York"}
userdata after encryption: {name: "John", age: 31, city: "New York"}
安全警告:您的代码使用硬编码的加密密钥,仅供演示,请勿在生产中使用:
<?php
$cypherMethod = 'AES-256-CBC';
$key = 'WHATEVER'; // ### Security warning: don't use a hard coded key in production
$userdata = '{name: "John", age: 31, city: "New York"}';
echo 'userdata before encryption: ' . $userdata . PHP_EOL;
// Then we generate a random Initialization Vector - which is stored with record in DB
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cypherMethod));
// Now we run the encryption process and convert output to Base64 to make DB storage easier
$userdata = openssl_encrypt($userdata, $cypherMethod, $key, $options=0, $iv);
$userdata = base64_encode($userdata);
//$cypherMethod = 'AES-256-CBC';
//$key = 'WHATEVER';
//$iv = 'GRABBED FROM DB RECORD';
$userdataDec = base64_decode($userdata);
$userdataDec = openssl_decrypt($userdataDec, $cypherMethod, $key, $options=0, $iv);
echo 'userdata after encryption: ' . $userdataDec . PHP_EOL;
?>