Cryptdes.php 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace com;
  3. /**
  4. * 对称加密解密
  5. */
  6. class Cryptdes
  7. {
  8. // 加密方式
  9. const METHOD = 'AES-256-CBC';
  10. public $key;
  11. public $error = '';
  12. public $ivStatus;
  13. public function __construct($key, $ivStatus = true)
  14. {
  15. if (!function_exists('openssl_encrypt') || !function_exists('openssl_decrypt')) {
  16. $this->error = '未启用 openssl 扩展,请开启。';
  17. }
  18. $this->ivStatus = $ivStatus;
  19. $this->key = $key;
  20. }
  21. /**
  22. * 加密
  23. */
  24. public function encrypt($data)
  25. {
  26. $str_padded = json_encode($data);
  27. if (strlen($str_padded) % 16) {
  28. $str_padded = str_pad($str_padded, strlen($str_padded) + 16 - strlen($str_padded) % 16, "\0");
  29. }
  30. if ($this->ivStatus) {
  31. $iv = $this->makeIv();
  32. $code = openssl_encrypt($str_padded, SELF::METHOD, $this->key, OPENSSL_NO_PADDING, $iv);
  33. return [
  34. 'iv' => base64_encode($iv),
  35. 'code' => base64_encode($code)
  36. ];
  37. } else {
  38. $code = openssl_encrypt($str_padded, SELF::METHOD, $this->key, OPENSSL_NO_PADDING);
  39. return base64_encode($code);
  40. }
  41. }
  42. /**
  43. * 解密
  44. */
  45. public function decrypt($code, $iv = '')
  46. {
  47. $code = base64_decode($code);
  48. $iv = base64_decode($iv);
  49. $res = openssl_decrypt($code, SELF::METHOD, $this->key, OPENSSL_NO_PADDING, $iv);
  50. return json_decode(trim($res), true);
  51. }
  52. /**
  53. * 生成 初始化向量 iv
  54. */
  55. public function makeIv()
  56. {
  57. $ivlen = openssl_cipher_iv_length(SELF::METHOD);
  58. return openssl_random_pseudo_bytes($ivlen);
  59. }
  60. }