суббота, 3 августа 2013 г.

PHP: Class for encryption / decryption

PHP: Class for encryption / decryption



  1. class Encryption {
  2.  
  3. const CYPHER = MCRYPT_RIJNDAEL_256;
  4. const MODE = MCRYPT_MODE_CBC;
  5. const KEY = 'anysecretkey';
  6.  
  7. public function encrypt($plaintext) {
  8. $td = mcrypt_module_open(self::CYPHER, '', self::MODE, '');
  9. $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
  10. mcrypt_generic_init($td, self::KEY, $iv);
  11. $crypttext = mcrypt_generic($td, $plaintext);
  12. mcrypt_generic_deinit($td);
  13. return base64_encode($iv . $crypttext);
  14. }
  15.  
  16. public function decrypt($crypttext) {
  17. $crypttext = base64_decode($crypttext);
  18. $plaintext = '';
  19. $td = mcrypt_module_open(self::CYPHER, '', self::MODE, '');
  20. $ivsize = mcrypt_enc_get_iv_size($td);
  21. $iv = substr($crypttext, 0, $ivsize);
  22. $crypttext = substr($crypttext, $ivsize);
  23. if ($iv) {
  24. mcrypt_generic_init($td, self::KEY, $iv);
  25. $plaintext = mdecrypt_generic($td, $crypttext);
  26. }
  27. return trim($plaintext);
  28. }
  29.  
  30. }
  31.  
  32. // Using example:
  33. // $encrypted_string = Encryption::encrypt('2');
  34. // $decrypted_string = Encryption::decrypt($encrypted_string);
  35. ?>

Комментариев нет:

Отправить комментарий

Постоянные читатели

Популярные сообщения