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