I referred nodejs encryption mentioned in https://stackoverflow.com/a/65072352/4910936 and i could encrypt and while decrypting getting error ""Error: Unsupported state or unable to authenticate data"
var crypto = require('crypto');
console.log('AES GCMC 256 String encryption with PBKDF2 derived key');
var plaintext = 'The quick brown fox jumps over the lazy dog';
console.log('plaintext: ', plaintext);
const cryptoConfig = {
cipherAlgorithm: 'aes-256-gcm',
masterKey: 'somekey',
iterations: 65535,
keyLength: 32,
saltLength: 16,
ivLength: 12,
tagLength: 16,
digest: 'sha512'
}
var ciphertext = encrypt(plaintext);
console.log('ciphertext: ', ciphertext);
decrypt(ciphertext)
function encrypt(content) {
const salt = crypto.randomBytes(cryptoConfig.saltLength);
console.log("salt : ", salt)
const iv = crypto.randomBytes(cryptoConfig.ivLength);
console.log("iv : ", iv)
const key = crypto.pbkdf2Sync(cryptoConfig.masterKey, salt, cryptoConfig.iterations,
cryptoConfig.keyLength, cryptoConfig.digest);
const cipher = crypto.createCipheriv(cryptoConfig.cipherAlgorithm, key, iv);
const encrypted = Buffer.concat([cipher.update(content, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
console.log("tag : ", tag)
// ### put the auth tag at the end of encrypted
//const encdata = Buffer.concat([salt, iv, tag, encrypted]).toString('base64');
const encdata = Buffer.concat([salt, iv, encrypted, tag]).toString('base64');
return encdata;
}
function decrypt(encdata){
///decrypt
// base64 decoding
const bData = Buffer.from(encdata, 'base64');
// convert data to buffers
const salt1 = bData.slice(0, 16);
const iv1 = bData.slice(16, 32);
const tag1 = bData.slice(32, 48);
const text1 = bData.slice(48);
// derive key using; 32 byte key length
// const key = crypto.pbkdf2Sync(cryptoConfig.masterkey, salt , 2145, 32, 'sha512');
const key1 = crypto.pbkdf2Sync(cryptoConfig.masterKey, salt1, cryptoConfig.iterations,
cryptoConfig.keyLength, cryptoConfig.digest)
// AES 256 GCM Mode
const decipher = crypto.createDecipheriv('aes-256-gcm', key1, iv1);
decipher.setAuthTag(tag1);
// encrypt the given text
const decrypted = decipher.update(text1, 'binary', 'utf8') + decipher.final('utf8');
console.log(decrypted)
}
From error it looks like I messed up while separating IV, salt from the encrypted data and thus not matching with what used while encrypting.