jonlev03
jonlev03

Reputation: 45

getting different values when encrypting and decrypting values in crypto-js

I am trying to make an authentication system for an online store, and to do this I am encrypting passwords with crypto-js. When testing my authentication script I realized that when I encrypt a password and then decrypt it I get a different result.


//Register
router.post("/register", async (req, res) => {
  const newUser = new User({
    username: req.body.username,
    email: req.body.email,
    password: CryptoJS.AES.encrypt(
      req.body.password,
      process.env.PASS_SEC
    ).toString(),
  });
  try {
    const savedUser = await newUser.save({ w: 1 });
    res.status(201).json(savedUser);
  } catch (err) {
    res.status(500).json(err);
  }
});

//Login
router.post("/login", async (req, res) => {
  try {
    const user = await User.findOne({ username: req.body.username });
    !user && res.status(401).json("Incorrect Username");
    const password = await CryptoJS.AES.decrypt(
      user.password,
      process.env.PASS_SEC
    ).toString();
    console.log(password);
    if (password !== req.body.password) {
      res.status(401).json("Incorrect Password");
    } else {
      res.status(200).json(user);
    }
  } catch (err) {
    res.status(500).json(err);
  }
});

my code is listed above. I can't seem to figure out what is going on.

for example if I encrypt 123456789, when decrypted I will get 313233343536373839.

Upvotes: 0

Views: 767

Answers (1)

jonlev03
jonlev03

Reputation: 45

When looking into the issue I found that the error was related to converting the hashed password to a string. Giving CryptoJS.enc.Utf8 to toString() as a parameter fixes the issue.

Upvotes: 1

Related Questions