使用SJCL用Javascript加密并用PHP解密 [英] Encrypt in Javascript with SJCL and decrypt in PHP

查看:113
本文介绍了使用SJCL用Javascript加密并用PHP解密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Javascript加密一些数据,并在将其发送到php服务器后将其解密。

I want to encrypt some data in Javascript and after sending it the php server it could be decrypted.

我打算使用JS加密库作为SJCL: http://crypto.stanford.edu/sjcl/ 。到目前为止,我可以使用JS加密我的数据并通过ajax发布。
这样的我的JS代码。

I'm planig to use JS encryption library as SJCL : http://crypto.stanford.edu/sjcl/ . Up to now I can encrypt my data in JS and send it via ajax post. my JS code lool like this.

sjcl.encrypt('a_key','secured_message');

我的问题是如何在php中解密数据。如果有可能,请向我展示如何使用示例代码。 (请注意:SSL对我来说不是一种选择,现在我打算使用KEY作为每个请求生成的随机数)。

My question is how do I decrypt my data in php. If it is possible show me how to do it with an example code. (note: SSL is not a option for me, and now I'm planning to use the KEY as generated random number per each request)

谢谢

推荐答案

PHP 7.1.0最后为iv和aad参数 BUT 添加了openssl支持,它错误地强制了12字节的iv长度。

PHP 7.1.0 finally adds openssl support for iv and aad parameters BUT it incorrectly enforces a 12 byte iv length.

在您的示例中,我们按以下方式加密:

In your example, we encrypt as follows:

var sjcl = require('./sjcl');
console.log(sjcl.encrypt('a_key', 'secured_message', { mode: 'ccm', iv: sjcl.random.randomWords(3, 0) }));

要获取:

{"iv":"YAKkgmNCcVawQtiB","v":1,"iter":10000,"ks":128,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"CwEDE4PXBzY=","ct":"pJ7nmnAGXiC9AD29OADlpFdFl0d/MxQ="}

因此,给定:

$password = 'a_key';
$input = json_decode('{"iv":"YAKkgmNCcVawQtiB","v":1,"iter":10000,"ks":128,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"CwEDE4PXBzY=","ct":"pJ7nmnAGXiC9AD29OADlpFdFl0d/MxQ="}', true);

我们可以在PHP 7.1.0中解密,如下所示:

We can decrypt in PHP 7.1.0 as follows:

$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);

这篇关于使用SJCL用Javascript加密并用PHP解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆