UNPKG

node-ciphers

Version:

Lightweight AES and DES encryption library for Node.js, featuring flexible encoding, multiple cipher modes, and TypeScript support.

62 lines (59 loc) 2.57 kB
import { randomBytes } from 'node:crypto'; import { BaseAesCipher } from './base/index.mjs'; class Ccm 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); } } } export { Ccm }; //# sourceMappingURL=ccm.mjs.map