· 6 years ago · Sep 12, 2019, 10:42 AM
1var crypto = require('crypto'),
2 algorithm = 'aes-128-cbc',
3 password = 'zW7f5YXELwlZMEDvkaeGe1nu51QbAwhB';
4var secretKey = 'zW7f5YXELwlZMEDvkaeGe1nu51QbAwhB';
5
6// var crypto = require('crypto'),
7// algorithm = 'aes-256-ctr',
8// password = 'd6F3Efeq';
9 const key = crypto.createHash('sha256').update(password).digest('base64').substr(0, 16);
10
11function encrypt(buffer){
12 var cipher = crypto.createCipher(algorithm,key)
13 var crypted = Buffer.concat([cipher.update(buffer),cipher.final()]);
14 return crypted;
15}
16
17function decrypt(buffer){
18 var decipher = crypto.createDecipher(algorithm,key)
19 var dec = Buffer.concat([decipher.update(buffer) , decipher.final()]);
20 return dec;
21}
22
23 function aesDecrypt (value) {
24 // try {
25 const encryptedText = Buffer.from(value, 'hex');
26 console.log("encryptedText",encryptedText ,encryptedText.toString());
27 const key = crypto.createHash('sha256').update(secretKey).digest('base64').substr(0, 16);
28 // decipher the string
29 console.log("key",key);
30 const decipher = crypto.createDecipher(algorithm, Buffer.from(key));
31 console.log("decipher",decipher);
32 let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
33 console.log("decrypted",decrypted, decrypted.length);
34 decrypted += decipher.final();
35 console.log("decrypted",decrypted, decrypted.length);
36 return decrypted;
37 // } catch (err) {
38 // // in case failed decryption, return the encrypted itself
39 // return value;
40
41 // }
42}
43function aesEncrypt(value) {
44 // try {
45 const key = crypto.createHash('sha256').update(secretKey).digest('base64').substr(0, 16);
46 console.log("key",key,Buffer.from(key));
47 const cipher = crypto.createCipher(algorithm, Buffer.from(key));
48 // cipher.setAutoPadding(false)
49 let crypted = cipher.update(value, 'utf8', 'hex');
50 console.log("crypted_______________",crypted);
51 crypted += cipher.final('hex');
52 console.log("crypted",crypted,"_________________", "+++++++",crypted.toString('hex'), value);
53 return crypted.toString('hex');
54 // } catch (err) {
55 // console.log('aesEncryptError', { value, err });
56 // // in case failed encryption, return the value itself
57 // return value;
58 // }
59}
60// var hw = encrypt(new Buffer("NAM_DEP_TRAI_28", "utf8"))
61// outputs hello world
62// console.log(hw.toString());
63// console.log(decrypt(hw).toString('utf8'));
64aesEncrypt("NAM_DEP_TRAI_28");
65aesDecrypt("788b395a68ec33f0ff10d2a790c6c235");
66// aesDecrypt("1bddc75575ea788075fe18538d8e665a")