Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

express - Encrypting multiple variables at once using Crypto in Node.JS

I am trying to encrypt variables sent in a POST request in Node.js but I am getting an error, "UnhandledPromiseRejectionWarning: Error: Trying to add data in unsupported state at Cipheriv.update". I am trying to encrypt data sent from the client and store it in a database as part of a registration page. Below is my code.

router.post('/', async (req, res) => {
  let algorithm = "aes-192-cbc"; //algorithm to use
  let encryptionPassword = "password";
  const key = crypto.scryptSync(encryptionPassword, 'salt', 24); //create key

  const iv = crypto.randomBytes(16); // generate different ciphertext everytime
  const cipher = crypto.createCipheriv(algorithm, key, iv);
  const decipher = crypto.createDecipheriv(algorithm, key, iv);
  let encryptedFN = cipher.update(req.body.firstName, 'utf8', 'hex') + cipher.final('hex'); // ENCRYPT HERE
  let encryptedLN = cipher.update(req.body.lastName, 'utf8', 'hex') + cipher.final('hex');
  let encryptedUN = cipher.update(req.body.username, 'utf8', 'hex') + cipher.final('hex');
  let encryptedEM = cipher.update(req.body.email, 'utf8', 'hex') + cipher.final('hex'); 
  let decryptedFN = decipher.update(encryptedFN, 'hex', 'utf8') + decipher.final('utf8'); //Deciphered text
  let decryptedLN = decipher.update(encryptedLN, 'hex', 'utf8') + decipher.final('utf8');
  let decryptedUN = decipher.update(encryptedUN, 'hex', 'utf8') + decipher.final('utf8');
  let decryptedEM = decipher.update(encryptedEM, 'hex', 'utf8') + decipher.final('utf8');
      
      let password = await req.body.password;
      
      try {    
        const hashedPassword = await bcrypt.hash(password, 10);
        let sql = "INSERT INTO account (username, first_name, last_name, email_address, password) " +
        "VALUES ('"+ encryptedUN +"', '"+ encryptedFN +"', '"+ encryptedLN +"', '"+ encryptedEM +"','"+ hashedPassword +"')";
        con.query(sql, function(error, result) {
          if (error) throw err;
          console.log('Success');
        });
      }catch(error){
        console.log(error);
      }
    });

Is it possible to encrypt multiple variables at once to be inserted in a database? And is it possible to decrypt them for use in a different location? I would appreciate your help as I am not used to encryption and find it quite an intriguing topic, Thanks for your time.

question from:https://stackoverflow.com/questions/65852187/encrypting-multiple-variables-at-once-using-crypto-in-node-js

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

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...