This repository was archived by the owner on Dec 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEncryption.php
More file actions
92 lines (82 loc) · 3.2 KB
/
Copy pathEncryption.php
File metadata and controls
92 lines (82 loc) · 3.2 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
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
/*
* Encrypts and decrypts the given string into an AES string
*/
require_once 'ConfigManager.php';
class Encryption
{
private $php_version;
private $cipher = null;
private $iv = null;
private $previousCipher = null;
private $previousIV = null;
public function __construct()
{
$this->php_version = phpversion();
$configManager = new ConfigManager("mysql.conf");
$this->cipher = $configManager->getConfigItemValue("encryption", "cipher", null);
if ($this->cipher == null || empty($this->cipher))
{
throw new Exception("Encryption cipher cannot be null. Ensure that it is specified in a section call encryption in the configuration file");
}
$this->iv = $configManager->getConfigItemValue("encryption", "iv", null);
if ($this->iv == null || empty($this->iv))
{
throw new Exception("Encryption iv cannot be null. Ensure that it is specified in a sectioned called encryption in the configuration file");
}
}
function resetKeysToDefaultKeys()
{
}
function encrypt($data)
{
if ($this->version[0] === "5")
{
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->cipher, $this->addpadding($data), MCRYPT_MODE_CBC, $this->iv));
}
else
{
return base64_encode(openssl_encrypt($data, 'AES-256-CBC', $this->cipher, OPENSSL_RAW_DATA, $this->iv));
}
}
private function addpadding($string, $blocksize = 16)
{
$len = strlen($string);
$pad = $blocksize - ($len % $blocksize);
$string .= str_repeat(chr($pad), $pad);
return $string;
}
private function strippadding($string)
{
$slast = ord(substr($string, -1));
$slastc = chr($slast);
$pcheck = substr($string, -$slast);
if(@preg_match("/$slastc{".$slast."}/", $string)){
$string = substr($string, 0, strlen($string)-$slast);
return $string;
} else {
throw new Exception("Strip padding failed. Likely not encrypted");
}
}
function decrypt($data)
{
try
{
if ($this->version[0] === "5")
{
$decoded = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->cipher, $data, MCRYPT_MODE_CBC, $this->iv);
$base64Decoded = @base64_decode($data);
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->cipher, $base64Decoded, MCRYPT_MODE_CBC, $this->iv);
return $this->strippadding($decrypted);
}
else
{
return $this->strippadding(openssl_decrypt(base64_decode($data), 'AES-256-CBC', $this->cipher, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $this->iv));
}
}
catch (Exception $e)
{
throw new Exception("Failed to decrypt");
}
}
}