1

Why does the following code throw up a DecipherFinal error in crypto -

  var crypto = require('crypto');
  c=new Date;
  x= (c.getTime()+"."+c.getMilliseconds()).toString()+".uIn";
  key = 'sevsolut'
        , plaintext = x
        , cipher = crypto.createCipher('aes-256-cbc', key)
        , decipher = crypto.createDecipher('aes-256-cbc', key);
  cipher.update(plaintext, 'utf8', 'base64');
  var encryptedPassword = cipher.final('base64')

  decipher.update(encryptedPassword, 'base64', 'utf8');
  var decryptedPassword = decipher.final('utf8');

  console.log('encrypted :', encryptedPassword);
  console.log('decrypted :', decryptedPassword);
gevorg
  • 4,835
  • 4
  • 35
  • 52
digster
  • 392
  • 5
  • 20

1 Answers1

2

You need to take the output from update:

var crypto = require('crypto');
c=new Date();
x= (c.getTime()+"."+c.getMilliseconds()).toString()+".uIn";
key = "sevsolut"
      , plaintext = x
      , cipher = crypto.createCipher('aes-256-cbc', key)
      , decipher = crypto.createDecipher('aes-256-cbc', key);
var encryptedPassword = cipher.update(plaintext, 'utf8', 'base64');
encryptedPassword += cipher.final('base64')

var decryptedPassword = decipher.update(encryptedPassword, 'base64', 'utf8');
decryptedPassword += decipher.final('utf8');

console.log('encrypted :', encryptedPassword);
console.log('decrypted :', decryptedPassword);
laktak
  • 57,064
  • 17
  • 134
  • 164
  • @chris..it worked perfectly :) ..however would like to point out one thing.. the code in question seems to work perfectly for strings of certain length(try it with a small simple string)..only when it goes above certain length is I guess when we have to employ adding the update step..can u shed some light on it? – digster Apr 04 '13 at 10:38
  • Not sure what you mean. Update returns the enciphered contents, and can be called many times with new data as it is streamed - final returns any remaining enciphered contents. – laktak Apr 04 '13 at 11:03
  • i meant say use x= "simple" as the plaintext input..then the code in the question works perfectly..however if x= some big string..then the code in the question fails and we have to proceed according to your example.... – digster Apr 04 '13 at 12:42
  • 1
    Encryption is done block by block. If you don't put in enough for a block the update function won't return anything. – laktak Apr 04 '13 at 18:14