UNPKG

1.89 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const crypto = require("crypto");
4const lodash_1 = require("lodash");
5class Crypt {
6 static decrypt(encrypted, password) {
7 const bData = Buffer.from(encrypted, 'base64');
8 const salt = bData.slice(0, 64 /* IV_START */);
9 const iv = bData.slice(64 /* IV_START */, 80 /* TAG_START */);
10 const tag = bData.slice(80 /* TAG_START */, 96 /* TEXT_START */);
11 const text = bData.slice(96 /* TEXT_START */);
12 const key = crypto.pbkdf2Sync(password, salt, 16384 /* KEY_ITERATIONS */, 32 /* KEY_LEN */, "sha512" /* HASH */);
13 const decipher = crypto.createDecipheriv("aes-256-gcm" /* CIPHER */, key, iv);
14 decipher.setAuthTag(tag);
15 const out = decipher.update(text, 'binary', 'utf8') + decipher.final('utf8');
16 if (!out) {
17 throw new Error('Unable to decrypt');
18 }
19 return out;
20 }
21 static decryptVar(v, password) {
22 return Crypt.decrypt(v.__encrypted, password);
23 }
24 static encrypt(text, password) {
25 const iv = crypto.randomBytes(16 /* IV_RANDOM_BYTES */);
26 const salt = crypto.randomBytes(64 /* SALT_RANDOM_BYTES */);
27 const key = crypto.pbkdf2Sync(password, salt, 16384 /* KEY_ITERATIONS */, 32 /* KEY_LEN */, "sha512" /* HASH */);
28 const cipher = crypto.createCipheriv("aes-256-gcm" /* CIPHER */, key, iv);
29 const encrypted = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
30 const authTag = cipher.getAuthTag();
31 return Buffer.concat([salt, iv, authTag, encrypted]).toString('base64');
32 }
33 static encryptVar(text, password) {
34 return { __encrypted: Crypt.encrypt(text, password) };
35 }
36 static isEncrypted(v) {
37 return !!v && lodash_1.isObject(v) && typeof v.__encrypted === 'string';
38 }
39}
40exports.Crypt = Crypt;