0

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()
Akshay
  • 1
  • 1
  • `salt+authTag+encryptedData` in `encrypt()` implicitly performs a UTF-8 decoding of the individual parts, which corrupts the data. Instead a concatenation of the raw data should be done with `Buffer.concat()`. In `decrypt()` the data should be separated using `subarray()`. – Topaco Oct 22 '22 at 19:52
  • @Topaco works – Akshay Oct 23 '22 at 05:32

0 Answers0