使用Javascript库SJCL加密,使用PHP解密

时间:2017-04-29 17:22:04

标签: javascript php encryption cryptography

我正在使用此库:https://github.com/bitwiseshiftleft/sjcl

我想加密字符串客户端,通过URL传递它,然后在后端解密它。

这是JS:

# Using proposed method
In [104]: df2.dot(df1.T)
Out[104]: 
    0   1
0  67  52
1  32  42
2  72  60

结果。

的console.log(明文)

<script src="https://bitwiseshiftleft.github.io/sjcl/sjcl.js"></script>
<script>
var ciphertext = sjcl.encrypt("password", "Hello World!")
var plaintext = sjcl.decrypt("password", ciphertext)
console.log(ciphertext)
console.log(plaintext)
</script>

的console.log(密文)

{"iv":"XA+HFebsM7WiVy0Ko8EEuA==","v":1,"iter":1000,"ks":128,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"f4BX8a9fUPM=","ct":"a4LesnrsT7C6MmkxZifSw7FsDyI="}

正如您所看到的,加密和解密按照JS的预期工作。当我尝试使用PHP解密它时出现问题:

Hello World!

$password = 'password'; $input = json_decode('{"iv":"XA+HFebsM7WiVy0Ko8EEuA==","v":1,"iter":1000,"ks":128,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"f4BX8a9fUPM=","ct":"a4LesnrsT7C6MmkxZifSw7FsDyI="}', true); $digest = hash_pbkdf2('sha256', $password, base64_decode($input['salt']), $input['iter'], 16, true); $cipher = $input['cipher'] . '-' . $input['ks'] . '-' . $input['mode']; $ct = substr(base64_decode($input['ct']), 0, - $input['ts'] / 8); $tag = substr(base64_decode($input['ct']), - $input['ts'] / 8); $iv = base64_decode($input['iv']); $adata = $input['adata']; $dt = openssl_decrypt($ct, $cipher, $digest, OPENSSL_RAW_DATA, $iv, $tag, $adata); var_dump($dt); while ($msg = openssl_error_string()) { echo $msg . "\n"; } 的结果是var_dump($dt),这是false无法解密字符串时发生的情况。 当然,我错过了一些东西,任何人都可以帮我注意它是什么?

1 个答案:

答案 0 :(得分:2)

使用模式“ gcm”和128位iv时,它已经运行。

  var key = 'password';
  var p = { mode: 'gcm', iv: sjcl.random.randomWords(4, 0) };
  var encrypted = sjcl.encrypt(key, 'Hello World', p);

这会导致输出,例如:

{"iv":"/Jyo0DNWt0CNUW6AYkpnBw==","v":1,"iter":10000,"ks":128,"ts":64,"mode":"gcm","adata":"","cipher":"aes","salt":"jFSuZEEICq8=","ct":"7+M0Wv79zKXu4SUYJPZAIIBYgw=="}

此JSON输出用作PHP中的输入:

$input = json_decode('<JSON output from above goes here>', true);

可以像上面的示例代码中提到的那样传递给解密:

$password = 'password';
$digest   = hash_pbkdf2('sha256', $password, base64_decode($input['salt']), 
$input['iter'], 0, true);
$cipher   = $input['cipher'] . '-' . $input['ks'] . '-' . $input['mode'];
$ct       = substr(base64_decode($input['ct']), 0, - $input['ts'] / 8);
$tag      = substr(base64_decode($input['ct']), - $input['ts'] / 8);
$iv       = base64_decode($input['iv']);
$adata    = $input['adata'];

$dt = openssl_decrypt($ct, $cipher, $digest, OPENSSL_RAW_DATA, $iv, $tag, $adata);
var_dump($dt);

这对于使用PHP 7.1.9版本的我来说是有效的