aes-universal-node
Version:
Node.js implementation of aes-universal
121 lines (120 loc) • 2.84 kB
JavaScript
import { AbstractCbcCipher as d, AbstractGcmCipher as l, AesCipher as g } from "aes-universal";
import i from "crypto";
const 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 y extends d {
/**
* Creates a new NodeCbcCipher instance
* @param randomBytes - Function to generate random bytes
*/
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 A extends l {
/**
* Creates a new NodeGcmCipher instance
* @param randomBytes - Function to generate random bytes
*/
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 C extends g {
/**
* Creates a new instance of NodeAesCipher.
*
* @param randomBytes - Function that generates cryptographically secure random bytes
* Must implement the RandomBytes interface from aes-universal
*/
constructor(h) {
super({
cbc: y,
gcm: A,
randomBytes: h
});
}
}
const b = (a = 32) => new Uint8Array(i.randomBytes(a));
export {
C as NodeAesCipher,
y as NodeCbcCipher,
A as NodeGcmCipher,
u as keyBitLengthToGCMType,
b as nodeRandomBytes
};