Iam using node crypto to encrypt files but it gives me error - "Unsupported state or unable to authenticate data" Iam using AuthTag or else it just decrypts to random text. I have not used encoding cause i wanted to encrypt all types of files txt,png,md,etc
const app = {
encrypt(data, password) {
const salt = crypto.randomBytes(16);
const key = crypto.scryptSync(password, salt, 32, { N: 16384 });
const cipher = crypto.createCipheriv('aes-256-gcm', key, salt)
const encryptedData = Buffer.concat([cipher.update(data), cipher.final()]);
const authTag = cipher.getAuthTag();
return salt+authTag+encryptedData;
},
decrypt(data, password) {
const salt = data.slice(0,16);
const authTag = data.slice(16,32);
const encData = data.slice(32,data.length);
const key = crypto.scryptSync(password, salt, 32, { N: 16384 });
const decipher = crypto.createDecipheriv('aes-256-gcm', key, salt);
decipher.setAuthTag(authTag);
const plainText = Buffer.concat([decipher.update(encData), decipher.final()]);
return plainText;
}
}
const fileLoc = './sample.txt';
const password = 'password';
const file = {
encrypt() {
fs.readFile(fileLoc, (err, data) => {
if (err) return console.log('File not found.');
if (data) {
const cipherText = app.encrypt(data,password);
fs.writeFileSync(fileLoc, cipherText);
console.log('Done');
}
})
},
decrypt() {
fs.readFile(fileLoc, (err, data) => {
if (err) console.log('File not found.')
if (data) {
const plainText = app.decrypt(data,password);
fs.writeFileSync(fileLoc, plainText);
console.log('Done');
}
})
}
}
file.encrypt()
file.decrypt()
Via Active questions tagged javascript - Stack Overflow https://ift.tt/KFMx9E7
Comments
Post a Comment