CryptoUtil.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace PhpZip\Util;
  3. use PhpZip\Exception\RuntimeException;
  4. /**
  5. * Crypto Utils.
  6. *
  7. * @internal
  8. */
  9. class CryptoUtil
  10. {
  11. /**
  12. * Returns random bytes.
  13. *
  14. * @param int $length
  15. *
  16. * @throws \Exception
  17. *
  18. * @return string
  19. *
  20. * @deprecated Use random_bytes()
  21. */
  22. final public static function randomBytes($length)
  23. {
  24. return random_bytes($length);
  25. }
  26. /**
  27. * Decrypt AES-CTR.
  28. *
  29. * @param string $data Encrypted data
  30. * @param string $key Aes key
  31. * @param string $iv Aes IV
  32. *
  33. * @return string Raw data
  34. */
  35. public static function decryptAesCtr($data, $key, $iv)
  36. {
  37. if (\extension_loaded('openssl')) {
  38. $numBits = \strlen($key) * 8;
  39. /** @noinspection PhpComposerExtensionStubsInspection */
  40. return openssl_decrypt($data, 'AES-' . $numBits . '-CTR', $key, \OPENSSL_RAW_DATA, $iv);
  41. }
  42. if (\extension_loaded('mcrypt')) {
  43. return mcrypt_decrypt(\MCRYPT_RIJNDAEL_128, $key, $data, 'ctr', $iv);
  44. }
  45. throw new RuntimeException('Extension openssl or mcrypt not loaded');
  46. }
  47. /**
  48. * Encrypt AES-CTR.
  49. *
  50. * @param string $data Raw data
  51. * @param string $key Aes key
  52. * @param string $iv Aes IV
  53. *
  54. * @return string Encrypted data
  55. */
  56. public static function encryptAesCtr($data, $key, $iv)
  57. {
  58. if (\extension_loaded('openssl')) {
  59. $numBits = \strlen($key) * 8;
  60. /** @noinspection PhpComposerExtensionStubsInspection */
  61. return openssl_encrypt($data, 'AES-' . $numBits . '-CTR', $key, \OPENSSL_RAW_DATA, $iv);
  62. }
  63. if (\extension_loaded('mcrypt')) {
  64. return mcrypt_encrypt(\MCRYPT_RIJNDAEL_128, $key, $data, 'ctr', $iv);
  65. }
  66. throw new RuntimeException('Extension openssl or mcrypt not loaded');
  67. }
  68. }