forked from chris-rock/node-crypto-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto-gcm.js
32 lines (28 loc) · 883 Bytes
/
crypto-gcm.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Nodejs encryption with GCM
// Does not work with nodejs v0.10.31
var crypto = require('crypto'),
algorithm = 'aes-256-gcm',
password = '3zTvzr3p67VC61jmV54rIYu1545x4TlY',
// do not use a global iv for production,
// generate a new one for each encryption
iv = '60iP0h6vJoEa'
function encrypt(text) {
var cipher = crypto.createCipheriv(algorithm, password, iv)
var encrypted = cipher.update(text, 'utf8', 'hex')
encrypted += cipher.final('hex');
var tag = cipher.getAuthTag();
return {
content: encrypted,
tag: tag
};
}
function decrypt(encrypted) {
var decipher = crypto.createDecipheriv(algorithm, password, iv)
decipher.setAuthTag(encrypted.tag);
var dec = decipher.update(encrypted.content, 'hex', 'utf8')
dec += decipher.final('utf8');
return dec;
}
var hw = encrypt("hello world")
// outputs hello world
console.log(decrypt(hw));