欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php使用3des加密的代码(兼容.net)

程序员文章站 2022-06-05 18:08:04
...
  1. class Crypt3Des
  2. {
  3. private $key = "";
  4. private $iv = "";
  5. /**
  6. * 构造,传递二个已经进行base64_encode的KEY与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. *加密
  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. *解密
  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两个版本)