diff --git a/common-libs/common/src/services/EncryptionService.ts b/common-libs/common/src/services/EncryptionService.ts index d36f5385..9b8d33f4 100644 --- a/common-libs/common/src/services/EncryptionService.ts +++ b/common-libs/common/src/services/EncryptionService.ts @@ -5,6 +5,7 @@ const createHash = require('create-hash/browser') const ENCRYPTION_ALGORITHM = 'aes-256-cbc' const IV_LENGTH = 16 +const IV_LENGTH_GCM = 12 const KEY_LENGTH = 32 const createCipher = (suite: string, key: unknown, iv: unknown, isDecipher = false) => { let cipherType = 'createCipheriv' @@ -50,24 +51,32 @@ const normalizeKey = (key: string): Buffer | undefined => { } export class EncryptionService { - static async encrypt(data: string, key: string, encyption_algo: string = ENCRYPTION_ALGORITHM) { + static async encrypt(data: string, key: string, encryption_algo: string = ENCRYPTION_ALGORITHM) { + const iv_length = encryption_algo.endsWith('-gcm') ? IV_LENGTH_GCM : IV_LENGTH const keyBuffer = normalizeKey(key) const dataBuffer = Buffer.from(data, undefined) - const iv = await randomBytes(IV_LENGTH) + const iv = await randomBytes(iv_length) - const cipher = createCipheriv(encyption_algo, keyBuffer, iv) + const cipher = createCipheriv(encryption_algo, keyBuffer, iv) const encryptedData = Buffer.concat([cipher.update(dataBuffer), cipher.final()]) - return Buffer.concat([iv, encryptedData]).toString('hex') + return encryption_algo.endsWith('-gcm') ? + `${Buffer.concat([iv, encryptedData]).toString('hex')}-${cipher.getAuthTag().toString('hex')}` : + Buffer.concat([iv, encryptedData]).toString('hex') } - static decrypt(data: string, key: string, encyption_algo: string = ENCRYPTION_ALGORITHM) { - const dataBuffer = Buffer.from(data, 'hex') + static decrypt(data: string, key: string, encryption_algo: string = ENCRYPTION_ALGORITHM) { + const iv_length = encryption_algo.endsWith('-gcm') ? IV_LENGTH_GCM : IV_LENGTH + const dataBuffer = encryption_algo.endsWith('-gcm') ? Buffer.from(data.substring(0, data.lastIndexOf('-')), 'hex') : Buffer.from(data, 'hex') const passwordBuffer = normalizeKey(key) - const iv = dataBuffer.slice(0, IV_LENGTH) - const encryptedDataWtihoutVector = dataBuffer.slice(IV_LENGTH) - - const decipher = createDecipheriv(encyption_algo, passwordBuffer, iv) + const iv = dataBuffer.slice(0, iv_length) + const encryptedDataWtihoutVector = dataBuffer.slice(iv_length) + + const decipher = createDecipheriv(encryption_algo, passwordBuffer, iv) + if (encryption_algo.endsWith('-gcm')) { + const authTag = Buffer.from(data.slice(data.lastIndexOf('-') + 1), 'hex') + decipher.setAuthTag(authTag) + } const decryptedBuffer = Buffer.concat([decipher.update(encryptedDataWtihoutVector), decipher.final()]) return decryptedBuffer.toString() }