-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencryption.php
71 lines (56 loc) · 2.01 KB
/
encryption.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
<?php
class Encryption
{
private $encryptionKey;
private $pepper;
public function __construct()
{
// Keys and Pepper values are taken from .env file
$this->encryptionKey = getenv('ENCRYPTION_KEY');
$this->pepper = getenv('PEPPER');
if (!$this->encryptionKey || !$this->pepper) {
throw new Exception("Encryption key or pepper is not set in environment variables.");
}
}
/**
* Encrypts data.
*/
public function encrypt(string $data): string
{
$iv = random_bytes(16); // AES-256-GCM for 16 byte IV
$salt = random_bytes(16); // For added security, the salt
// Key derivation
$key = hash_hmac('sha256', $this->encryptionKey . $salt, $this->pepper, true);
// Encryption with AES-256-GCM
$ciphertext = openssl_encrypt($data, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
if ($ciphertext === false) {
throw new Exception("Encryption failed.");
}
// Salt, combine IV and encrypted data
return base64_encode($salt . $iv . $tag . $ciphertext);
}
/**
* Decrypts encrypted data.
*/
public function decrypt(string $encryptedData): string
{
$decoded = base64_decode($encryptedData);
if ($decoded === false) {
throw new Exception("Invalid encoded data.");
}
// Salt, separate IV and data
$salt = substr($decoded, 0, 16);
$iv = substr($decoded, 16, 16);
$tag = substr($decoded, 32, 16);
$ciphertext = substr($decoded, 48);
// Key derivation
$key = hash_hmac('sha256', $this->encryptionKey . $salt, $this->pepper, true);
// Decryption with AES-256-GCM
$data = openssl_decrypt($ciphertext, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
if ($data === false) {
throw new Exception("Decryption failed.");
}
return $data;
}
}
?>