shetabit /
AES
| 1 | <?php |
||
| 2 | |||
| 3 | class AES |
||
| 4 | { |
||
| 5 | /** |
||
| 6 | * @var string |
||
| 7 | */ |
||
| 8 | protected $cipher; |
||
| 9 | |||
| 10 | /** |
||
| 11 | * @var string |
||
| 12 | */ |
||
| 13 | protected $key; |
||
| 14 | |||
| 15 | /** |
||
| 16 | * @var null | string |
||
| 17 | */ |
||
| 18 | protected $iv; |
||
| 19 | |||
| 20 | /** |
||
| 21 | * AES constructor. |
||
| 22 | * |
||
| 23 | * @param string $key |
||
| 24 | * @param string $cipher |
||
| 25 | * @param null|string $iv |
||
| 26 | */ |
||
| 27 | public function __construct($key, $cipher = 'AES-256-CBC', $iv = null) |
||
| 28 | { |
||
| 29 | $this->cipher = $cipher; |
||
| 30 | $this->key = $key; |
||
| 31 | $this->iv = $iv; |
||
| 32 | } |
||
| 33 | |||
| 34 | /** |
||
| 35 | * Encrypt the given data. |
||
| 36 | * |
||
| 37 | * @param string $data |
||
| 38 | * @return string |
||
| 39 | * |
||
| 40 | */ |
||
| 41 | public function encrypt($data) |
||
| 42 | { |
||
| 43 | if ($this->iv) { |
||
| 44 | $iv = $this->iv; |
||
| 45 | } else { |
||
| 46 | $iv = base64_encode(random_bytes(openssl_cipher_iv_length($this->cipher))); |
||
| 47 | } |
||
| 48 | |||
| 49 | $encrypted = openssl_encrypt($data, $this->cipher, base64_decode($this->key), 0, base64_decode($iv)); |
||
| 50 | |||
| 51 | if ($this->iv == null) { |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 52 | return $encrypted . ':' . $iv; |
||
| 53 | } |
||
| 54 | return $encrypted; |
||
| 55 | } |
||
| 56 | |||
| 57 | /** |
||
| 58 | * Decrypt the given data. |
||
| 59 | * |
||
| 60 | * @param string $data |
||
| 61 | * @param bool $randomIv |
||
| 62 | * @return string |
||
| 63 | */ |
||
| 64 | public function decrypt($data, $randomIv = false) |
||
| 65 | { |
||
| 66 | if ($randomIv) { |
||
| 67 | // To decrypt, separate the encrypted data from the initialization vector ($iv). |
||
| 68 | $parts = explode(':', $data); |
||
| 69 | $encrypted = $parts[0]; |
||
| 70 | $iv = base64_decode($parts[1]); |
||
| 71 | } else { |
||
| 72 | $encrypted = $data; |
||
| 73 | $iv = base64_decode($this->iv); |
||
| 74 | } |
||
| 75 | $decrypted = openssl_decrypt($encrypted, $this->cipher, base64_decode($this->key), 0, $iv); |
||
| 76 | return $decrypted; |
||
| 77 | } |
||
| 78 | } |
||
| 79 |