Aes.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace Biz\Account;
  3. /**
  4. * aes 加密 解密类库
  5. * @by singwa
  6. * Class Aes
  7. * @package app\common\lib
  8. */
  9. class Aes {
  10. /**
  11. * var string $method 加解密方法,可通过openssl_get_cipher_methods()获得
  12. */
  13. protected $method;
  14. /**
  15. * var string $secret_key 加解密的密钥
  16. */
  17. protected $secret_key;
  18. /**
  19. * var string $iv 加解密的向量,有些方法需要设置比如CBC
  20. */
  21. protected $iv;
  22. /**
  23. * var string $options (不知道怎么解释,目前设置为0没什么问题)
  24. */
  25. protected $options;
  26. /**
  27. * 构造函数
  28. *
  29. * @param string $key 密钥
  30. * @param string $method 加密方式
  31. * @param string $iv iv向量
  32. * @param mixed $options 还不是很清楚
  33. *
  34. */
  35. public function __construct($key, $method = 'AES-128-ECB', $iv = '', $options = 0)
  36. {
  37. // key是必须要设置的
  38. $this->secret_key = isset($key) ? $key : 'morefun';
  39. $this->method = $method;
  40. $this->iv = $iv;
  41. $this->options = $options;
  42. }
  43. /**
  44. * 加密方法,对数据进行加密,返回加密后的数据
  45. *
  46. * @param string $data 要加密的数据
  47. *
  48. * @return string
  49. *
  50. */
  51. public function encrypt($data)
  52. {
  53. return openssl_encrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
  54. }
  55. /**
  56. * 解密方法,对数据进行解密,返回解密后的数据
  57. *
  58. * @param string $data 要解密的数据
  59. *
  60. * @return string
  61. *
  62. */
  63. public function decrypt($data)
  64. {
  65. return openssl_decrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
  66. }
  67. }