Home > Backend Development > PHP Tutorial > PHP uses 3des encrypted code (compatible with .net)

PHP uses 3des encrypted code (compatible with .net)

WBOY
Release: 2016-07-25 09:05:47
Original
1081 people have browsed it
  1. class Crypt3Des
  2. {
  3. private $key = "";
  4. private $iv = "";
  5. /**
  6. * Construct, pass two base64_encoded KEY and IV
  7. *
  8. * @param string $key
  9. * @param string $iv
  10. */
  11. function __construct ($key, $iv)
  12. {
  13. if (empty($key) || empty($iv)) {
  14. echo 'key and iv is not valid';
  15. exit();
  16. }
  17. $this->key = $key;
  18. $this->iv = $iv;
  19. }
  20. /**
  21. *Encryption
  22. * @param $value
  23. * @return
  24. */
  25. public function encrypt ($value)
  26. {
  27. $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
  28. $iv = base64_decode($this->iv);
  29. $value = $this->PaddingPKCS7($value);
  30. $key = base64_decode($this->key);
  31. mcrypt_generic_init($td, $key, $iv);
  32. $ret = base64_encode(mcrypt_generic($td, $value));
  33. mcrypt_generic_deinit($td);
  34. mcrypt_module_close($td);
  35. return $ret;
  36. }
  37. /**
  38. *Decrypt
  39. * @param $value
  40. * @return
  41. */
  42. public function decrypt ($value)
  43. {
  44. $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
  45. $iv = base64_decode($this->iv);
  46. $key = base64_decode($this->key);
  47. mcrypt_generic_init($td, $key, $iv);
  48. $ret = trim(mdecrypt_generic($td, base64_decode($value)));
  49. $ret = $this->UnPaddingPKCS7($ret);
  50. mcrypt_generic_deinit($td);
  51. mcrypt_module_close($td);
  52. return $ret;
  53. }
  54. private function PaddingPKCS7 ($data)
  55. {
  56. $block_size = mcrypt_get_block_size('tripledes', 'cbc');
  57. $padding_char = $block_size - (strlen($data) % $block_size);
  58. $data .= str_repeat(chr($padding_char), $padding_char);
  59. return $data;
  60. }
  61. private function UnPaddingPKCS7 ($text)
  62. {
  63. $pad = ord($text{strlen($text) - 1});
  64. if ($pad > strlen($text)) {
  65. return false;
  66. }
  67. if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {
  68. return false;
  69. }
  70. return substr($text, 0, - 1 * $pad);
  71. }
  72. }
  73. ?>
复制代码

您可能感兴趣的文章: php DES加密解密的代码一例 关于des加密与解密实现方法(php net两个版本)



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template