-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsafe.js
More file actions
50 lines (40 loc) · 1.5 KB
/
safe.js
File metadata and controls
50 lines (40 loc) · 1.5 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const crypto = require('crypto');
module.exports = {
encrypt: (data, pass) => {
let password = new Buffer.alloc(32);
password.write(pass, 'utf8');
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-gcm', password, iv);
let encrypted = cipher.update(data, 'utf8', 'hex');
encrypted += cipher.final('hex');
const tag = cipher.getAuthTag();
var eHash = crypto.createHash('sha1');
eHash.setEncoding('hex');
eHash.update(data, 'utf8');
return `${encrypted}:${iv.toString('hex')}:${tag.toString('hex')}:${eHash.digest('hex')}`;
},
decrypt: (encoded, pass) => {
let password = new Buffer.alloc(32);
password.write(pass, 'utf8');
const chunks = encoded.split(':');
const data = chunks[0];
const iv = new Buffer.from(chunks[1], 'hex');
const tag = new Buffer.from(chunks[2], 'hex');
const hash = chunks[3];
const decipher = crypto.createDecipheriv('aes-256-gcm', password, iv);
decipher.setAuthTag(tag);
let decrypted = null;
try {
decrypted = decipher.update(data, 'hex', 'utf8');
decrypted += decipher.final('utf8');
} catch (error) {
}
var dHash = crypto.createHash('sha1');
dHash.setEncoding('hex');
dHash.update(decrypted, 'utf8');
return {
data: decrypted,
check: dHash.digest('hex') === hash
};
}
};