Crypt.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. class Zend_Crypt
  3. {
  4. const TYPE_OPENSSL = 'openssl';
  5. const TYPE_HASH = 'hash';
  6. const TYPE_MHASH = 'mhash';
  7. protected static $_type = null;
  8. protected static $_supportedAlgosOpenssl = array(
  9. 'md2',
  10. 'md4',
  11. 'mdc2',
  12. 'rmd160',
  13. 'sha',
  14. 'sha1',
  15. 'sha224',
  16. 'sha256',
  17. 'sha384',
  18. 'sha512'
  19. );
  20. protected static $_supportedAlgosMhash = array(
  21. 'adler32',
  22. 'crc32',
  23. 'crc32b',
  24. 'gost',
  25. 'haval128',
  26. 'haval160',
  27. 'haval192',
  28. 'haval256',
  29. 'md4',
  30. 'md5',
  31. 'ripemd160',
  32. 'sha1',
  33. 'sha256',
  34. 'tiger',
  35. 'tiger128',
  36. 'tiger160'
  37. );
  38. public static function hash($algorithm, $data, $binaryOutput = false)
  39. {
  40. $algorithm = strtolower($algorithm);
  41. if (function_exists($algorithm)) {
  42. return $algorithm($data, $binaryOutput);
  43. }
  44. self::_detectHashSupport($algorithm);
  45. $supportedMethod = '_digest' . ucfirst(self::$_type);
  46. $result = self::$supportedMethod($algorithm, $data, $binaryOutput);
  47. }
  48. protected static function _detectHashSupport($algorithm)
  49. {
  50. if (function_exists('hash')) {
  51. self::$_type = self::TYPE_HASH;
  52. if (in_array($algorithm, hash_algos())) {
  53. return;
  54. }
  55. }
  56. if (function_exists('mhash')) {
  57. self::$_type = self::TYPE_MHASH;
  58. if (in_array($algorithm, self::$_supportedAlgosMhash)) {
  59. return;
  60. }
  61. }
  62. if (function_exists('openssl_digest')) {
  63. if ($algorithm == 'ripemd160') {
  64. $algorithm = 'rmd160';
  65. }
  66. self::$_type = self::TYPE_OPENSSL;
  67. if (in_array($algorithm, self::$_supportedAlgosOpenssl)) {
  68. return;
  69. }
  70. }
  71. require_once 'Zend/Crypt/Exception.php';
  72. throw new Zend_Crypt_Exception('\'' . $algorithm . '\' is not supported by any available extension or native function');
  73. }
  74. protected static function _digestHash($algorithm, $data, $binaryOutput)
  75. {
  76. return hash($algorithm, $data, $binaryOutput);
  77. }
  78. protected static function _digestMhash($algorithm, $data, $binaryOutput)
  79. {
  80. $constant = constant('MHASH_' . strtoupper($algorithm));
  81. $binary = mhash($constant, $data);
  82. if ($binaryOutput) {
  83. return $binary;
  84. }
  85. return bin2hex($binary);
  86. }
  87. protected static function _digestOpenssl($algorithm, $data, $binaryOutput)
  88. {
  89. if ($algorithm == 'ripemd160') {
  90. $algorithm = 'rmd160';
  91. }
  92. return openssl_digest($data, $algorithm, $binaryOutput);
  93. }
  94. }