Javascript encryption with SJCL and decryption in PHP

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

I plan to use the encryption JS library as SJCL: http://crypto.stanford.edu/sjcl/ . So far, I can encrypt my data in JS and send it via ajax post. my js code is like this.

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

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

thanks

+3
source share
2 answers

PHP 7.1.0 finally adds openssl support for the iv and aad parameters, but this incorrectly enters a length of 12 bytes.

In your example, we encrypt the following:

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

To obtain:

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

So, considering:

 $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
source

Although this does not fully answer your question, I should:

  • suggest using crypto-js as the most standard JS encryption, hashing and KDF library (this means that the provided methods are compatible with PHP equivalents)
  • suppose you read at least the first lines in this article where you will find out why all the benefits of using Javascript cryptography are a false sense of security.
0
source

Source: https://habr.com/ru/post/1274408/


All Articles