CypherMCrypt.php

  1. <?php
  2.  
  3. class CypherMCrypt {
  4.  
  5. //---------------------------------------------
  6. // Symmetric key
  7.  
  8. private static $algorithm = MCRYPT_RIJNDAEL_128; // http://php.net/manual/en/mcrypt.ciphers.php
  9. private static $mode = MCRYPT_MODE_CBC; // http://php.net/manual/en/mcrypt.constants.php
  10.  
  11. public static function encode($text) {
  12. $iv = self::getIV();
  13. $encrypted = @mcrypt_encrypt(self::$algorithm, self::getKey(), self::addPadding($text), self::$mode, $iv);
  14. $binary = $iv.$encrypted;
  15. return base64_encode($binary);
  16. }
  17.  
  18. public static function decode($text) {
  19. $binary = base64_decode($text);
  20. $size = self::getSize();
  21. $iv = substr($binary, 0, $size);
  22. $encrypted = substr($binary, $size);
  23. $text = mcrypt_decrypt(self::$algorithm, self::getKey(), $encrypted, self::$mode, $iv);
  24. return self::stripPadding($text);
  25. }
  26.  
  27. //---------------------------------------------
  28. // Info
  29.  
  30. private static function getKey() { // 32 bytes in hexadecimal
  31. return pack('H*', "0123456789abcdef00112233445566778899aabbccddeeff0123456789abcdef");
  32. }
  33. private static function getIV() {
  34. //return pack('H*', "00000000000000000000000000000000");
  35. return mcrypt_create_iv(self::getSize(), MCRYPT_DEV_URANDOM);
  36. }
  37. private static function getSize() {
  38. return mcrypt_get_iv_size(self::$algorithm, self::$mode);
  39. }
  40.  
  41. //---------------------------------------------
  42. // Helpers
  43.  
  44. private static function addPadding($string) {
  45. $blocksize = self::getSize();
  46. $len = strlen($string);
  47. $pad = $blocksize - ($len % $blocksize);
  48. $string .= str_repeat(chr($pad), $pad);
  49. return $string;
  50. }
  51. private static function stripPadding($string) {
  52. $slast = ord(substr($string, -1));
  53. $slastc = chr($slast);
  54. $pcheck = substr($string, -$slast);
  55. if (preg_match("/$slastc{".$slast."}/", $string)) {
  56. $string = substr($string, 0, strlen($string)-$slast);
  57. return $string;
  58. }
  59. else return false;
  60. }
  61.  
  62. }
  63.  

Proinf.net