Skip to content

Commit f1862fc

Browse files
committed
security feature ready
1 parent 660da8f commit f1862fc

File tree

2 files changed

+34
-7
lines changed

2 files changed

+34
-7
lines changed

src/Libraries/Security.php

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -38,15 +38,21 @@ class Security
3838
*/
3939
public static function encrypt(string $plaintext): string
4040
{
41-
$plaintext = hex2bin($plaintext);
42-
if (!$plaintext) {
43-
throw new \Exception("failed to convert plaintext into bin");
41+
$charset = array_merge(
42+
range('0', '9'),
43+
range('a', 'z'),
44+
range('A', 'Z'),
45+
);
46+
$ivArr = [];
47+
for ($i = 0; $i < 16; $i++) {
48+
$ivArr[] = $charset[random_int(0,61)];
4449
}
45-
$ecrypted = openssl_encrypt($plaintext, "AES-128-CBC", env('SECURITY_KEY'), OPENSSL_ZERO_PADDING, env('SECURITY_IV_KEY'));
50+
$iv = implode('', $ivArr);
51+
$ecrypted = openssl_encrypt($plaintext, "AES-128-CBC", env('SECURITY_KEY'), OPENSSL_RAW_DATA, $iv);
4652
if (!$ecrypted) {
4753
throw new \Exception("failed to encrypt string");
4854
}
49-
return bin2hex($ecrypted);
55+
return bin2hex($iv . $ecrypted);
5056
}
5157

5258
/**
@@ -59,8 +65,11 @@ public static function encrypt(string $plaintext): string
5965
*/
6066
public static function decrypt(string $encrypted): string
6167
{
62-
$binpin = hex2bin($encrypted);
63-
$decrypted = openssl_decrypt($binpin, "AES-128-CBC", env('SECURITY_KEY'), OPENSSL_ZERO_PADDING, env('SECURITY_IV_KEY'));
68+
69+
$ivHex = substr($encrypted,0,32);
70+
$iv = hex2bin($ivHex);
71+
$encrypted = substr($encrypted,32);
72+
$decrypted = openssl_decrypt(hex2bin($encrypted), "AES-128-CBC", env('SECURITY_KEY'), OPENSSL_RAW_DATA, $iv);
6473
if (!$decrypted) {
6574
throw new \Exception("failed to decrypt string");
6675
}

tests/Libraries/SecurityTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,27 @@ public function createApplication()
1616

1717
public function testEncrypt1(): void
1818
{
19+
putenv('SECURITY_KEY=123456789ABCDefg');
1920
$plain = 'beautiful soup';
2021
$encrypted = Security::encrypt($plain);
2122
$decrypted = Security::decrypt($encrypted);
2223
$this->assertEquals($plain, $decrypted);
2324
}
25+
26+
public function testDecrypt1(): void
27+
{
28+
putenv('SECURITY_KEY=0123456789abcdef');
29+
$encrypted = '69687168694E496177653970746B6834383021D52B533A55ECBA5BACC753055AD59F65DD091541A32FA262B3116CFDC3';
30+
$decrypted = Security::decrypt($encrypted);
31+
$this->assertEquals('AES CBC with secure random IV', $decrypted);
32+
}
33+
34+
public function testEncryptError(): void
35+
{
36+
$this->expectException(\Exception::class);
37+
putenv('SECURITY_KEY=0123456789abcd');
38+
$x = Security::encrypt('beautiful soup');
39+
putenv('SECURITY_KEY=0123456789abcd321');
40+
Security::decrypt($x);
41+
}
2442
}

0 commit comments

Comments
 (0)