Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Created by PhpStorm.
- * User: cly
- * Date: 2016-07-16
- * Time: 16:11
- */
- class AES {
- protected $password = "";
- function __construct($password=Null) {
- if (!$this->is_openssl()) {
- throw new Exception("Open-ssl not present.");
- }
- if ($password) {
- $this->$password = $password;
- } else {
- $this->$password = openssl_random_pseudo_bytes(128);
- }
- }
- function encrypt($data) {
- $method = $this->get_encryption_mode();
- $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
- $encrypted = openssl_encrypt($data, $method, $this->password, true, $iv);
- $string = "%s%s";
- $data = sprintf($string, $encrypted, $iv);
- return $data;
- }
- function decrypt ($data) {
- $method = "aes-256-cbc";
- $iv_len = openssl_cipher_iv_length($method);
- $iv = substr($data, -$iv_len);
- $data = substr($data, 0, strlen($data)-$iv_len);
- $decrypted = openssl_decrypt($data, $method, $this->password, true, $iv);
- return $decrypted;
- }
- function is_openssl() {
- $methods = ["openssl_get_cipher_methods",
- "openssl_random_pseudo_bytes",
- "openssl_encrypt",
- "openssl_get_cipher_methods"
- ];
- $exists = True;
- foreach ($methods as $m) {
- $exists = $exists && $m;
- }
- return $exists;
- }
- function get_encryption_mode () {
- $preferred = ["aes-256-cbc", "aes-256-ofb", "aes-256-cfb", "aes-256-ecb"];
- $method = "";
- $methods = openssl_get_cipher_methods();
- foreach ($preferred as $m) {
- if (in_array($m, $methods)) {
- $method = $m;
- break;
- }
- }
- return $method;
- }
- }
- $data = "I am a cow from mars that yells";
- $test = new AES("kel");
- $d = $test->encrypt($data);
- echo $test->decrypt($d), "\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement