aes-universal-node
Version:
Node.js implementation of aes-universal
2 lines (1 loc) • 1.7 kB
JavaScript
;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("aes-universal"),i=require("crypto"),u=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 l extends d.AbstractCbcCipher{constructor(h){super(h),this.encryptInternal=async({encRawKey:e,iv:c,plaintext:r})=>{const s=e.length*8,t=i.createCipheriv(`aes-${s}-cbc`,e,c),n=Buffer.concat([t.update(r),t.final()]);return new Uint8Array(n)},this.decryptInternal=async({encRawKey:e,iv:c,ciphertext:r})=>{const s=e.length*8,t=i.createDecipheriv(`aes-${s}-cbc`,e,c),n=Buffer.concat([t.update(r),t.final()]);return new Uint8Array(n)},this.generateTag=async({macRawKey:e,macData:c,keyBitLength:r})=>{const s=`sha${r<<1}`,t=i.createHmac(s,e);return t.update(c),new Uint8Array(t.digest()).slice(0,r>>>3)}}}class y extends d.AbstractGcmCipher{constructor(h){super(h),this.encryptInternal=async({encRawKey:e,iv:c,plaintext:r,aad:s})=>{const t=u(e.length<<3),n=i.createCipheriv(t,e,c);n.setAAD(s);const o=Buffer.concat([n.update(r),n.final()]),p=n.getAuthTag();return{ciphertext:new Uint8Array(o),tag:new Uint8Array(p)}},this.decryptInternal=async({encRawKey:e,iv:c,ciphertext:r,tag:s,aad:t})=>{const n=u(e.length<<3),o=i.createDecipheriv(n,e,c);o.setAAD(t),o.setAuthTag(s);const p=Buffer.concat([o.update(r),o.final()]);return new Uint8Array(p)}}}class g extends d.AesCipher{constructor(h){super({cbc:l,gcm:y,randomBytes:h})}}const A=(a=32)=>new Uint8Array(i.randomBytes(a));exports.NodeAesCipher=g;exports.NodeCbcCipher=l;exports.NodeGcmCipher=y;exports.keyBitLengthToGCMType=u;exports.nodeRandomBytes=A;