UNPKG

node-ciphers

Version:

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

62 lines (58 loc) 2.42 kB
'use strict'; const node_crypto = require('node:crypto'); const index = require('./base/index.cjs'); class Gcm extends index.BaseAesCipher { #ivLength; constructor(key, encodingOptions, ivLength = 12) { super(key, 'gcm', encodingOptions); this.#ivLength = ivLength; } decrypt(encryptedData, iv, authTag, 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, 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, ivLength = this.#ivLength, encodingOptions, cipherOptions) { const iv = node_crypto.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, ivLength = this.#ivLength, encodingOptions, cipherOptions) { try { return this.encrypt(JSON.stringify(data), authTagLength, ivLength, encodingOptions, cipherOptions); } catch (error) { return this.createErrorResult(error); } } } exports.Gcm = Gcm; //# sourceMappingURL=gcm.cjs.map