· 7 years ago · Feb 17, 2018, 01:40 PM
1'use strict';
2const crypto = require('crypto');
3
4class aes_crypto {
5 constructor(secret_key) {
6 this.IV_LENGTH = 16; // AES = 16 bytes
7 if(secret_key.length !== 32)
8 throw new Error('aes_crypto error param init secret_key.length !== 32');
9 this.ENCRYPTION_KEY = secret_key;
10 this.algoritm = 'aes-256-cbc';
11 }
12
13 encrypt(text) {
14 let iv = crypto.randomBytes(this.IV_LENGTH);
15 let cipher = crypto.createCipheriv(this.algoritm, Buffer.from(this.ENCRYPTION_KEY), iv);
16 let encrypted = Buffer.concat([cipher.update(text), cipher.final()]);
17
18 return iv.toString('hex') + ':' + encrypted.toString('hex');
19 }
20
21 decrypt(text) {
22 let textParts = text.split(':');
23 let iv = new Buffer(textParts.shift(), 'hex');
24 let encryptedText = Buffer.from(textParts.join(':'), 'hex');
25 let decipher = crypto.createDecipheriv(this.algoritm, Buffer.from(this.ENCRYPTION_KEY), iv);
26 let decrypted = decipher.update(encryptedText);
27 decrypted = Buffer.concat([decrypted, decipher.final()]);
28 return decrypted.toString();
29 }
30}
31
32
33module.exports = aes_crypto;