-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCryptor.php
More file actions
52 lines (44 loc) · 1.5 KB
/
Cryptor.php
File metadata and controls
52 lines (44 loc) · 1.5 KB
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
<?php
namespace OWC\PrefillGravityForms\Foundation;
class Cryptor
{
protected string $method = 'aes-128-ctr'; // default cipher method if none supplied
private string $key;
public function __construct(bool $method = false)
{
$key = \AUTH_KEY ?? php_uname();
if (ctype_print($key)) {
// convert ASCII keys to binary format
$this->key = openssl_digest($key, 'SHA256', true);
} else {
$this->key = $key;
}
if ($method) {
if (! in_array(strtolower($method), openssl_get_cipher_methods())) {
throw new \Exception(__METHOD__ . ": unrecognised cipher method: {$method}");
}
$this->method = $method;
}
}
protected function ivBytes()
{
return openssl_cipher_iv_length($this->method);
}
public function encrypt($data)
{
$iv = openssl_random_pseudo_bytes($this->ivBytes());
return bin2hex($iv) . openssl_encrypt($data, $this->method, $this->key, 0, $iv);
}
// decrypt encrypted string
public function decrypt($data)
{
$iv_strlen = 2 * $this->ivBytes();
if (preg_match("/^(.{" . $iv_strlen . "})(.+)$/", $data, $regs)) {
list(, $iv, $crypted_string) = $regs;
if (ctype_xdigit($iv) && 0 == strlen($iv) % 2) {
return openssl_decrypt($crypted_string, $this->method, $this->key, 0, hex2bin($iv));
}
}
return false; // failed to decrypt
}
}