Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 16th, 2012  |  syntax: None  |  size: 1.19 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Encrypt message in PHP, decrypt in JavaScript
  2. class Encryption
  3. {
  4. const CYPHER = 'blowfish';
  5. const MODE   = 'cbc';
  6. const KEY    = '26854571066639171754759502724211797107457520821';
  7.  
  8. public function encrypt($plaintext)
  9. {
  10.     $td = mcrypt_module_open(self::CYPHER, '', self::MODE, '');
  11.     $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
  12.     mcrypt_generic_init($td, self::KEY, $iv);
  13.     $crypttext = mcrypt_generic($td, $plaintext);
  14.     mcrypt_generic_deinit($td);
  15.     return $iv.$crypttext;
  16. }
  17.  
  18. public function decrypt($crypttext)
  19. {
  20.     $plaintext = '';
  21.     $td        = mcrypt_module_open(self::CYPHER, '', self::MODE, '');
  22.     $ivsize    = mcrypt_enc_get_iv_size($td);
  23.     $iv        = substr($crypttext, 0, $ivsize);
  24.     $crypttext = substr($crypttext, $ivsize);
  25.     if ($iv)
  26.     {
  27.         mcrypt_generic_init($td, self::KEY, $iv);
  28.         $plaintext = mdecrypt_generic($td, $crypttext);
  29.     }
  30.     return $plaintext;
  31. }
  32. }
  33.  
  34. $encrypted_string = Encryption::encrypt('this is a test');
  35. $decrypted_string = Encryption::decrypt($encrypted_string);
  36.  
  37. echo "encrypted: $encrypted_string<br>";
  38. echo "decrypted: $decrypted_string<br>";
  39.  
  40. encrypted: µ˜?r_¿ÖŸŒúw‰1‹Žn!úaH
  41. decrypted: this is a test