ImageCryptRepository.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /**
  3. * 图像加密解密.
  4. * @auth nj911<nj-x@gmail.com>
  5. * @date: 2021-04-18 15:36
  6. */
  7. namespace App\Repositories\Utils;
  8. use File;
  9. class ImageCryptRepository
  10. {
  11. /**
  12. * AES密钥,所有项目都代码里写死.
  13. * @var string
  14. */
  15. protected $secret = 'OlL7iiVrC23VWioD';
  16. /**
  17. * 算法.写死,不可变.
  18. * @var string
  19. */
  20. protected $cipher = 'AES-128-ECB';
  21. /**
  22. * 向量.
  23. * @var string
  24. */
  25. protected $iv = '';
  26. /**
  27. * 标记.
  28. * @var int
  29. */
  30. protected $option = OPENSSL_RAW_DATA;
  31. /**
  32. * 加密字节数据.
  33. * @param $raw
  34. * @param $toPath
  35. * @return bool|int
  36. */
  37. public function encodeRaw($raw)
  38. {
  39. return aes_encrypt($raw, $this->secret, $this->iv, $this->cipher, $this->option);
  40. }
  41. /**
  42. * 解密字节数据
  43. * @param $raw
  44. * @return string
  45. */
  46. public function decodeRaw($raw)
  47. {
  48. return aes_decrypt($raw, $this->secret, $this->iv, $this->cipher, $this->option);
  49. }
  50. /**
  51. * 加密并保存.
  52. * @param $raw
  53. * @param $toPath
  54. * @return bool|int
  55. */
  56. public function encode($raw, $toPath)
  57. {
  58. if (File::exists($toPath)) {
  59. File::delete($toPath);
  60. }
  61. return File::put($toPath, $this->encodeRaw($raw));
  62. }
  63. /**
  64. * 解密并保存.
  65. * @param $raw
  66. * @param $toPath
  67. * @return bool|int
  68. */
  69. public function decode($raw, $toPath)
  70. {
  71. if (File::exists($toPath)) {
  72. File::delete($toPath);
  73. }
  74. return File::put($toPath, $this->decodeRaw($raw));
  75. }
  76. }