CypherOpenSSL.php

  1. <?php
  2.  
  3. class CypherOpenSSL {
  4.  
  5. //---------------------------------------------
  6. // Symmetric key
  7.  
  8. private static $algorithm = "AES-256-CBC"; // Advanced Encryption System
  9. private static $options = OPENSSL_RAW_DATA;
  10.  
  11. public static function encode($text) {
  12. $iv = self::getIV();
  13. $encrypted = openssl_encrypt($text, self::$algorithm, self::getKey(), self::$options, $iv);
  14. $binary = $iv.$encrypted;
  15. return base64_encode($binary);
  16. }
  17.  
  18. public static function decode($text) {
  19. $binary = base64_decode($text);
  20. $size = self::getSize();
  21. $iv = substr($binary, 0, $size);
  22. $encrypted = substr($binary, $size);
  23. $text = openssl_decrypt($encrypted, self::$algorithm, self::getKey(), self::$options, $iv);
  24. return $text;
  25. }
  26.  
  27. //---------------------------------------------
  28. // Info
  29.  
  30. private static function getKey() { // 32 bytes in hexadecimal
  31. return pack('H*', "0123456789abcdef00112233445566778899aabbccddeeff0123456789abcdef");
  32. }
  33. private static function getIV() {
  34. //return pack('H*', "00000000000000000000000000000000");
  35. return openssl_random_pseudo_bytes(self::getSize()); // 16 bytes
  36. }
  37. private static function getSize() {
  38. return openssl_cipher_iv_length(self::$algorithm); // returns 16
  39. }
  40.  
  41. }
  42.  

Proinf.net