问题
I want to encrypt some data in Javascript and after sending it the php server it could be decrypted.
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');
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)
Thanks
回答1:
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) }));
To get:
{"iv":"YAKkgmNCcVawQtiB","v":1,"iter":10000,"ks":128,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"CwEDE4PXBzY=","ct":"pJ7nmnAGXiC9AD29OADlpFdFl0d/MxQ="}
So, given:
$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);
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);
回答2:
While this does not answers your question entirely, I have to:
- suggest using crypto-js as most standard complaint JS encryption, hashing and KDF library (that means that provided methods is compatibile with PHP equivalents )
- suggest that you read at least first lines of this article where you will learn why all gain from utilizing Javascript cryptography is false sense of security
来源:https://stackoverflow.com/questions/11982073/encrypt-in-javascript-with-sjcl-and-decrypt-in-php