Advertisement
Guest User

Untitled

a guest
Jul 16th, 2016
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.99 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: cly
  5.  * Date: 2016-07-16
  6.  * Time: 16:11
  7.  */
  8.  
  9. class AES {
  10.     protected $password = "";
  11.  
  12.     function __construct($password=Null) {
  13.         if (!$this->is_openssl()) {
  14.             throw new Exception("Open-ssl not present.");
  15.         }
  16.         if ($password) {
  17.             $this->$password = $password;
  18.         } else {
  19.             $this->$password = openssl_random_pseudo_bytes(128);
  20.         }
  21.     }
  22.  
  23.     function encrypt($data) {
  24.         $method = $this->get_encryption_mode();
  25.         $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
  26.         $encrypted = openssl_encrypt($data, $method, $this->password, true, $iv);
  27.         $string = "%s%s";
  28.         $data = sprintf($string, $encrypted, $iv);
  29.         return $data;
  30.     }
  31.     function decrypt ($data) {
  32.         $method = "aes-256-cbc";
  33.         $iv_len = openssl_cipher_iv_length($method);
  34.         $iv = substr($data, -$iv_len);
  35.         $data = substr($data, 0, strlen($data)-$iv_len);
  36.         $decrypted = openssl_decrypt($data, $method, $this->password, true, $iv);
  37.         return $decrypted;
  38.     }
  39.  
  40.     function is_openssl() {
  41.         $methods = ["openssl_get_cipher_methods",
  42.             "openssl_random_pseudo_bytes",
  43.             "openssl_encrypt",
  44.             "openssl_get_cipher_methods"
  45.         ];
  46.         $exists = True;
  47.         foreach ($methods as $m) {
  48.             $exists = $exists && $m;
  49.         }
  50.         return $exists;
  51.     }
  52.  
  53.     function get_encryption_mode () {
  54.         $preferred = ["aes-256-cbc", "aes-256-ofb", "aes-256-cfb", "aes-256-ecb"];
  55.         $method = "";
  56.         $methods = openssl_get_cipher_methods();
  57.         foreach ($preferred as $m) {
  58.  
  59.             if (in_array($m, $methods)) {
  60.                 $method = $m;
  61.                 break;
  62.             }
  63.         }
  64.         return $method;
  65.  
  66.     }
  67. }
  68.  
  69. $data = "I am a cow from mars that yells";
  70.  
  71. $test = new AES("kel");
  72. $d = $test->encrypt($data);
  73. echo $test->decrypt($d), "\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement