DataEncryption.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. /**
  3. * Copyright 2019 JD.COM
  4. *
  5. * Data Encryption Utility Class
  6. *
  7. * <P> Data Chunk Encryption Implementation.
  8. *
  9. * @version 1.0
  10. */
  11. namespace ACES\Common;
  12. class DataEncryption
  13. {
  14. private $iv;
  15. private $key;
  16. function __construct($key=NULL)
  17. {
  18. $this->iv = Crypto::secureRandom(Crypto::CIPHER_IV_SIZE);
  19. if ($key == NULL)
  20. $this->key = Crypto::secureRandom(Crypto::CIPHER_KEY_SIZE);
  21. else
  22. $this->key =$key;
  23. }
  24. function __destruct() {}
  25. public function exportKey()
  26. {
  27. return $this->key;
  28. }
  29. public function exportIv(){
  30. return $this->iv;
  31. }
  32. public function encrypt($pt)
  33. {
  34. $ct_data = openssl_encrypt($pt, Crypto::CIPHER_METHOD_AES_128_CBC, $this->key, OPENSSL_RAW_DATA, $this->iv);
  35. $ct = $this->iv . $ct_data;
  36. return $ct;
  37. }
  38. public function decrypt($ct)
  39. {
  40. $this->iv = substr($ct, 0, Crypto::CIPHER_IV_SIZE);
  41. $ct_data = substr($ct, Crypto::CIPHER_IV_SIZE, strlen($ct) - Crypto::CIPHER_IV_SIZE);
  42. $pt = openssl_decrypt($ct_data, Crypto::CIPHER_METHOD_AES_128_CBC, $this->key, OPENSSL_RAW_DATA, $this->iv);
  43. if($pt === FALSE)
  44. echo "\ndecrypt fail.";
  45. return $pt;
  46. }
  47. }