UNPKG

chaingate

Version:

A complete TypeScript library for connecting to and making transactions on different blockchains

66 lines 2.18 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Encrypted = exports.IncorrectPassword = void 0; const utils_1 = require("@noble/hashes/utils"); const aes_1 = require("@noble/ciphers/aes"); const Crypto_1 = require("../../../InternalUtils/Crypto"); const iterations = 600_000; const dkLen = 32; class IncorrectPassword extends Error { constructor() { super('Password is incorrect'); if (Error.captureStackTrace) Error.captureStackTrace(this, IncorrectPassword); this.name = this.constructor.name; } } exports.IncorrectPassword = IncorrectPassword; class Encrypted { iterations; dkLen; nonce; salt; data; cipher; constructor(params) { this.iterations = params.iterations; this.dkLen = params.dkLen; this.nonce = params.nonce; this.salt = params.salt; this.data = params.data; this.cipher = params.cipher; } static async encrypt(dataToEncrypt, password) { const cipher = 'aes-gcm'; const salt = (0, utils_1.randomBytes)(32); const nonce = (0, utils_1.randomBytes)(12); const derivedKey = await (0, Crypto_1.pbkdf2)({ iterations, dkLen, salt, password }); const data = (0, aes_1.gcm)(derivedKey, nonce).encrypt(dataToEncrypt); return new Encrypted({ iterations, dkLen, nonce, salt, data, cipher, }); } static async decrypt(encrypted, password) { const iterations = encrypted.iterations; const dkLen = encrypted.dkLen; const salt = encrypted.salt; const nonce = encrypted.nonce; const derivedKey = await (0, Crypto_1.pbkdf2)({ iterations, dkLen, salt, password }); try { return (0, aes_1.gcm)(derivedKey, nonce).decrypt(encrypted.data); } catch (ex) { if ('message' in ex && ex.message == 'aes/gcm: invalid ghash tag') throw new IncorrectPassword(); else throw ex; } } } exports.Encrypted = Encrypted; //# sourceMappingURL=Encrypted.js.map