Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

node.js - crypto decipher returning unknown characters when deciphering from base64 to utf-8

I'm building a encryption/decryption module for environment variables that has two functions

  1. encrypt the contents of .env & writes it to encrypted.env
  2. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...