I am implementing a basic encryption/decryption set of functions in nodejs and I keep getting the following error in the decryption part:
Error: Unsupported state or unable to authenticate data
This is my code so far:
import crypto from 'crypto'
import logger from './logger'
const ALGORITHM = 'aes-256-gcm'
export const encrypt = (keyBuffer, dataBuffer, aadBuffer) => {
// iv stands for "initialization vector"
const iv = Buffer.from(crypto.randomBytes(12), 'utf8')
logger.debug('iv: ', iv)
const encryptor = crypto.createCipheriv(ALGORITHM, keyBuffer, iv)
logger.debug('encryptor: ', encryptor)
logger.debug('dataBuffer: ', dataBuffer)
return Buffer.concat([iv, encryptor.update(dataBuffer, 'utf8'), encryptor.final()])
}
export const decrypt = (keyBuffer, dataBuffer, aadBuffer) => {
const iv = dataBuffer.slice(0, 96)
const decryptor = crypto.createDecipheriv(ALGORITHM, keyBuffer, iv)
return Buffer.concat([decryptor.update(dataBuffer.slice(96), 'utf8'), decryptor.final()])
}
My error happens in the last line of the decrypt function. I am storing the iv as part of the dataBuffer.
Thanks in advance!