Aec.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace toolkits;
  3. class Aec
  4. {
  5. /**
  6. * var string $method 加解密方法,可通过openssl_get_cipher_methods()获得
  7. */
  8. protected $method;
  9. /**
  10. * var string $secret_key 加解密的密钥
  11. */
  12. protected $secret_key;
  13. /**
  14. * var string $iv 加解密的向量,有些方法需要设置比如CBC
  15. */
  16. protected $iv;
  17. /**
  18. * var string $options (不知道怎么解释,目前设置为0没什么问题)
  19. */
  20. protected $options;
  21. /**
  22. * 构造函数
  23. *
  24. * @param string $key 密钥
  25. * @param string $method 加密方式
  26. * @param string $iv iv向量 初始化向量 16位字符串
  27. * @param mixed $options 0为默认模式,自动对明文进行 pkcs7 padding,且数据做 base64 编码处理
  28. *
  29. */
  30. public function __construct($key, $iv = null, $method = 'AES-128-CBC', $options = 0)
  31. {
  32. // key是必须要设置的
  33. $this->secret_key = isset($key) ? $key : 'yunxiekeji';
  34. $this->method = $method;
  35. $this->iv = $iv;
  36. $this->options = $options;
  37. }
  38. /**
  39. * 加密方法,对数据进行加密,返回加密后的数据
  40. *
  41. * @param string $data 要加密的数据
  42. *
  43. * @return string
  44. *
  45. */
  46. public function encrypt($data)
  47. {
  48. return base64_encode(openssl_encrypt($data, $this->method, $this->secret_key, $this->options, $this->iv));
  49. }
  50. /**
  51. * 解密方法,对数据进行解密,返回解密后的数据
  52. *
  53. * @param string $data 要解密的数据
  54. *
  55. * @return string
  56. *
  57. */
  58. public function decrypt($data)
  59. {
  60. return openssl_decrypt(base64_decode($data), $this->method, $this->secret_key, $this->options, $this->iv);
  61. }
  62. }