2

I'm encrypting/decrypting a string using the following functions:

function encrypt(text, pswrd){
  var cipher = crypto.createCipher(algorithm,pswrd),
      crypted = cipher.update(text,'utf8','hex');
      crypted += cipher.final('hex');
  return crypted;
}

function decrypt(text, pswrd){
  var decipher = crypto.createDecipher(algorithm,pswrd),
      dec = decipher.update(text,'hex','utf8');
      dec += decipher.final('utf8');
  return dec;
}

The password is being asked using inquirer, so the user input a password to encrypt and then should use the same to decrypt.

Everything works while the password matches, but the problem is when the password is wrong. I can't find a callback/method to handle the error that the console outputs then a decryption fails because of the wrong password. the terminal shows:

? Use same password: *
p�pP��X�B
��=�a�_��b��EyX��7�����X�y�����+�Rr�<��΅W��B�������am4r���+��v�
readline.js:924
            throw err;
            ^

SyntaxError: Unexpected token 
    at Object.parse (native)

How can I handle this error when a wrong password is used to decrypt?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Jorge Epuñan
  • 710
  • 7
  • 9
  • Have you tried `try {...} catch(e){...}` ? – Artjom B. Feb 15 '16 at 16:16
  • 1
    Possible duplicate of [Node.js Best Practice Exception Handling](http://stackoverflow.com/questions/7310521/node-js-best-practice-exception-handling) – BrTkCa Feb 15 '16 at 16:19
  • You don't normally get automatic integrity checking using ciphers like that. Which algorithm are you using? – Phil Feb 15 '16 at 17:03
  • @Phil_1984_ it's `algorithm = 'aes-256-ctr'` – Jorge Epuñan Feb 15 '16 at 18:37
  • 1
    You should look in to authenticated encryption or using an existing encryption library that handles authentication so you can catch incorrect password errors properly. – Phil Feb 15 '16 at 22:27

1 Answers1

-1

We have the same inquiry, I hope this help, What I did solution is.

cipher decryption has no callback for check password, but I made it simple, I create a token validator (which is also encrypted from cipher) every-time I received a data(which is also encrypted in cypher). token & "data" are encrypted in same password, if token(decryption from correct-password) is validated from my tokenValidator(hmac or web-token). then "data" is now valid to process from my server