Advertisement
Guest User

Untitled

a guest
Jun 21st, 2012
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ar crypto = require('crypto');
  2. var algorithm = 'aes-128-ecb';
  3. var key = '1234';
  4.  
  5. /*-----------------------------------------------------------*
  6.  * ENCRYPT: AES 128 bit, CBC                                 *
  7.  *-----------------------------------------------------------*/
  8.  var data = "jugs";
  9.  
  10.  var ciphertext = _encrypt(data, key, algorithm);
  11.  
  12.  console.log(ciphertext);
  13.  
  14.  
  15. /*-----------------------------------------------------------*
  16.  * DECRYPT: AES 128 bit, CBC                                 *
  17.  *-----------------------------------------------------------*/
  18.  
  19.  var plain = _decrypt(ciphertext, key, algorithm);
  20.  
  21.  
  22.  
  23. /********************************************************************
  24.                       IMPLEMENTING FUNCTIONS...
  25. ********************************************************************/
  26.  
  27. function _encrypt(data, key, algorithm)
  28. {
  29.   var clearEncoding = 'utf8';
  30.   var cipherEncoding = 'base64'; // hex, base64
  31.  
  32.   var cipher = crypto.createCipher(algorithm, key);
  33.   var cipherChunks = [];
  34.   cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
  35.   cipherChunks.push(cipher.final(cipherEncoding));
  36.  
  37.  return (cipherChunks);
  38. }
  39.  
  40. function _decrypt(ciphertext, key, algorithm)
  41. {
  42.   var clearEncoding = 'utf8';
  43.   var cipherEncoding = 'base64'; // hex, base64
  44.  
  45.   var decipher = crypto.createDecipher(algorithm, key);
  46.   var plainChunks = [];
  47.   for (var i = 0;i < ciphertext.length;i++) {
  48.    plainChunks.push(decipher.update(ciphertext[i], cipherEncoding, clearEncoding));
  49.   }
  50.   plainChunks.push(decipher.final(clearEncoding));
  51.   var plaintext = plainChunks.join('');
  52.  
  53.  return (plaintext);
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement