· 7 years ago · Jan 13, 2019, 08:46 PM
1function encrypt_decrypt($action, $string) {
2 $output = false;
3
4 $encrypt_method = "AES-256-CBC";
5$secret_key = 'This is my secret key';
6 $secret_iv = 'This is my secret iv';
7
8 // hash
9 $key = hash('sha256', $secret_key);
10
11 // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
12 $iv = substr(hash('sha256', $secret_iv), 0, 16);
13
14 if ( $action == 'encrypt' ) {
15 $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
16 $output = base64_encode($output);
17} else if( $action == 'decrypt' ) {
18 $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
19 }
20
21 return $output;
22}
23
24var crypto = require('crypto')
25 , key = 'This is my secret key'
26 , iv = 'This is my secret iv'
27 , plaintext = '2';
28
29 hashedKey = crypto.createHash('sha256').update(key, 'utf-8').digest('hex');
30 console.log('hashed key=', hashedKey);
31 // corresponds to the hashed key in PHP
32
33 hashedIv = crypto.createHash('sha256').update(iv, 'utf-8').digest('hex').substring(0,16);
34 console.log('hashed iv=', hashedIv);
35 // corresponds to the hashed iv in PHP
36
37 var buf = Buffer.from(teamId, 'base64');
38 console.log("buffer: " + buf);
39
40var decryptor = crypto.createDecipheriv("aes-256-cbc", hashedKey, hashedIv);
41 console.log("the shit: " + decryptor.update(buf, 'base64', 'utf8') + decryptor.final('utf8'));