UNPKG

aes-universal-node

Version:
107 lines (106 loc) 2.42 kB
import { AbstractCbcCipher as u, AbstractGcmCipher as d, AesCipher as l } from "aes-universal"; import i from "crypto"; const p = (a) => { switch (a) { case 128: return "aes-128-gcm"; case 192: return "aes-192-gcm"; case 256: return "aes-256-gcm"; default: throw new Error(`Invalid key bit length: ${a}`); } }; class g extends u { constructor() { super(...arguments), this.encryptInternal = async ({ encRawKey: e, iv: c, plaintext: n }) => { const s = e.length * 8, t = i.createCipheriv( `aes-${s}-cbc`, e, c ), r = Buffer.concat([ t.update(n), t.final() ]); return new Uint8Array(r); }, this.decryptInternal = async ({ encRawKey: e, iv: c, ciphertext: n }) => { const s = e.length * 8, t = i.createDecipheriv( `aes-${s}-cbc`, e, c ), r = Buffer.concat([ t.update(n), t.final() ]); return new Uint8Array(r); }, this.generateTag = async ({ macRawKey: e, macData: c, keyBitLength: n }) => { const s = `sha${n << 1}`, t = i.createHmac(s, e); return t.update(c), new Uint8Array(t.digest()).slice(0, n >>> 3); }; } } class y extends d { constructor() { super(...arguments), this.encryptInternal = async ({ encRawKey: e, iv: c, plaintext: n, aad: s }) => { const t = p(e.length << 3), r = i.createCipheriv(t, e, c); r.setAAD(s); const o = Buffer.concat([ r.update(n), r.final() ]), h = r.getAuthTag(); return { ciphertext: new Uint8Array(o), tag: new Uint8Array(h) }; }, this.decryptInternal = async ({ encRawKey: e, iv: c, ciphertext: n, tag: s, aad: t }) => { const r = p(e.length << 3), o = i.createDecipheriv(r, e, c); o.setAAD(t), o.setAuthTag(s); const h = Buffer.concat([ o.update(n), o.final() ]); return new Uint8Array(h); }; } } class m extends l { constructor() { super({ cbc: new g(), gcm: new y() }); } } const C = new m(), w = (a = 32) => new Uint8Array(i.randomBytes(a)); export { m as NodeAesCipher, g as NodeCbcCipher, y as NodeGcmCipher, p as keyBitLengthToGCMType, C as nodeAesCipher, w as nodeRandomBytes };