Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 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 reply this article.

OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...