@@ -38,15 +38,21 @@ class Security
38
38
*/
39
39
public static function encrypt (string $ plaintext ): string
40
40
{
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 )];
44
49
}
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 );
46
52
if (!$ ecrypted ) {
47
53
throw new \Exception ("failed to encrypt string " );
48
54
}
49
- return bin2hex ($ ecrypted );
55
+ return bin2hex ($ iv . $ ecrypted );
50
56
}
51
57
52
58
/**
@@ -59,8 +65,11 @@ public static function encrypt(string $plaintext): string
59
65
*/
60
66
public static function decrypt (string $ encrypted ): string
61
67
{
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 );
64
73
if (!$ decrypted ) {
65
74
throw new \Exception ("failed to decrypt string " );
66
75
}
0 commit comments