node-ciphers
Version:
Lightweight AES and DES encryption library for Node.js, featuring flexible encoding, multiple cipher modes, and TypeScript support.
59 lines (57 loc) • 2.24 kB
JavaScript
import { BaseAesCipher } from "./_internals/base/index.js";
import { randomBytes } from "node:crypto";
//#region src/aes/ccm.ts
var Ccm = class extends BaseAesCipher {
#authTagLength;
#ivLength;
constructor(key, encodingOptions, authTagLength = 16, ivLength = 12) {
super(key, "ccm", encodingOptions);
this.#authTagLength = authTagLength;
this.#ivLength = ivLength;
}
decrypt(encryptedData, iv, authTag, authTagLength = this.#authTagLength, encodingOptions, decipherOptions) {
try {
const decipher = this.createDecipher(this.dataToBuffer(iv, encodingOptions?.iv || this.encodingOptions.iv), {
authTagLength,
...decipherOptions
});
decipher.setAuthTag(this.dataToBuffer(authTag, encodingOptions?.authTag || this.encodingOptions.authTag));
return this.createOkResult(this.getDecipherResult(decipher, encryptedData, encodingOptions));
} catch (error) {
return this.createErrorResult(error);
}
}
decryptToJson(encryptedData, iv, authTag, authTagLength = this.#authTagLength, encodingOptions, decipherOptions) {
const result = this.decrypt(encryptedData, iv, authTag, authTagLength, encodingOptions, decipherOptions);
if (!result.ok) return result;
return this.parseJson(result.value);
}
encrypt(data, authTagLength = this.#authTagLength, ivLength = this.#ivLength, encodingOptions, cipherOptions) {
const iv = randomBytes(ivLength);
try {
const cipher = this.createCipher(iv, {
authTagLength,
...cipherOptions
});
const encryptedData = this.getCipherResult(cipher, data, encodingOptions);
return this.createOkResult({
authTag: cipher.getAuthTag().toString(encodingOptions?.authTag || this.encodingOptions.authTag),
authTagLength,
data: encryptedData,
iv: iv.toString(encodingOptions?.iv || this.encodingOptions.iv)
});
} catch (error) {
return this.createErrorResult(error);
}
}
encryptJson(data, authTagLength = this.#authTagLength, ivLength = this.#ivLength, encodingOptions, cipherOptions) {
try {
return this.encrypt(JSON.stringify(data), authTagLength, ivLength, encodingOptions, cipherOptions);
} catch (error) {
return this.createErrorResult(error);
}
}
};
//#endregion
export { Ccm };
//# sourceMappingURL=ccm.js.map