I'm building a encryption/decryption module for environment variables that has two functions
- encrypt the contents of .env & writes it to encrypted.env
- decrypt the contents of encrypted.env & write it to .env
I've run into an issue where the first line of .env is unknown characters after decryption.
original contents of .env
STAGE="DEVELOPMENT"
USERNAME="Greggo"
PASSWORD="myPassw0rd?1234"
encrypted.env:
PEGeGD40pJoLBN2cQvFgPm/KrWxMakRkKkhbUlzQdsNF8zrmr0w5dUsEVINRfXPPM23W8No8HF5uCzqRCMG98g5MHDZkHpXE1s4/cevGTv0=
decrypted .env:
?~#?A??YHQ??//NT"
USERNAME="Greggo"
PASSWORD="myPassw0rd?1234"
encrypt.js
fs.readFile('./.env', 'utf-8', (err, data) => {
if (err) {
throw err;
}
console.log(data);
crypto.scrypt('glfgmkjldpg90d9gd88k3kfs;fsdl;f99sfFKkdl;dlda', 'salt', 24, (err, key) => {
if (err) {
throw err;
}
crypto.randomFill(new Uint8Array(16), (err, iv) => {
if (err) {
throw err;
}
const cipher = crypto.createCipheriv('aes-192-cbc', key, iv);
let encrypted = cipher.update(data, 'utf-8', 'base64');
encrypted += cipher.final('base64');
console.log(encrypted);
fs.writeFile('./encrypted.env', encrypted, (err, data) => {
if (err) {
throw err;
}
console.log(data);
});
});
})
});
decrypt.js
fs.readFile('./encrypted.env', 'utf-8', (err, encryptedData) => {
if (err) {
throw err;
}
console.log(encryptedData);
const key = crypto.scryptSync('glfgmkjldpg90d9gd88k3kfs;fsdl;f99sfFKkdl;dlda', 'salt', SALT_ROUNDS);
const iv = Buffer.alloc(16, 0);
const decipher = crypto.createDecipheriv('aes-192-cbc', key, iv);
let decrypted = decipher.update(encryptedData, 'base64', 'utf-8');
decrypted += decipher.final('utf-8');
console.log(decrypted);
fs.writeFile('./.env', decrypted, (err, decryptedData) => {
if (err) {
throw err;
}
console.log(decryptedData);
});
});
question from:
https://stackoverflow.com/questions/65944612/crypto-decipher-returning-unknown-characters-when-deciphering-from-base64-to-utf 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…