1+ <?php
2+
3+ class AES256Encryption
4+ {
5+
6+ private static string $ OPENSSL_CIPHER_NAME = "aes-256-cbc " ; //Name of OpenSSL Cipher
7+ private static int $ CIPHER_KEY_LEN = 32 ; // 32 bytes (256 bits)
8+
9+ static function getRandomIV (): string
10+ {
11+ $ characters = '0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*()-=_+ABCDEFGHIJKLMNOPQRSTUVWXYZ ' ;
12+ $ charactersLength = strlen ($ characters );
13+ $ randomString = '' ;
14+ for ($ i = 0 ; $ i < AES256Encryption::$ CIPHER_KEY_LEN ; $ i ++)
15+ {
16+ $ randomString .= $ characters [rand (0 , $ charactersLength - 1 )];
17+ }
18+
19+ return $ randomString ;
20+ }
21+
22+ /**
23+
24+ * Encrypt data using AES Cipher (CBC) with 256 bit key
25+ * @param type $key - key to use should be 32 bytes long (256 bits)
26+ * @param type $data - data to encrypt
27+ * @return encrypted data in base64 encoding with iv attached at end after a :
28+ */
29+ static function encrypt (string $ key , string $ data ): string
30+ {
31+ $ iv = AES256Encryption::getRandomIV ();
32+
33+ if (strlen ($ key ) < AES256Encryption::$ CIPHER_KEY_LEN )
34+ {
35+ $ key = str_pad ($ key , AES256Encryption::$ CIPHER_KEY_LEN , "0 " ); //0 pad to len 32
36+ }
37+ else if (strlen ($ key ) > AES256Encryption::$ CIPHER_KEY_LEN )
38+ {
39+ $ key = substr ($ str , 0 , AES256Encryption::$ CIPHER_KEY_LEN ); //truncate to 32 bytes
40+ }
41+
42+ $ encodedEncryptedData = base64_encode (openssl_encrypt ($ data , AES256Encryption::$ OPENSSL_CIPHER_NAME , $ key , OPENSSL_RAW_DATA , $ iv ));
43+ $ encodedIV = base64_encode ($ iv );
44+ $ encryptedPayload = $ encodedEncryptedData . ": " . $ encodedIV ;
45+ return $ encryptedPayload ;
46+ }
47+
48+ /**
49+ * Decrypt data using AES Cipher (CBC) with 256 bit key
50+ * @param type $key - key to use should be 32 bytes long (256 bits)
51+ * @param type $data - data to be decrypted in base64 encoding with iv attached at the end after a :
52+ * @return decrypted data
53+ */
54+ static function decrypt (string $ key , string $ data ): string
55+ {
56+ if (strlen ($ key ) < AES256Encryption::$ CIPHER_KEY_LEN )
57+ {
58+ $ key = str_pad ($ key , AES256Encryption::$ CIPHER_KEY_LEN , "0 " ); //0 pad to len 32
59+ }
60+ else if (strlen ($ key ) > AES256Encryption::$ CIPHER_KEY_LEN )
61+ {
62+ $ key = substr ($ str , 0 , AES256Encryption::$ CIPHER_KEY_LEN ); //truncate to 32 bytes
63+ }
64+
65+ $ parts = explode (': ' , $ data ); //Separate Encrypted data from iv.
66+ $ decryptedData = openssl_decrypt (base64_decode ($ parts [0 ]), AES256Encryption::$ OPENSSL_CIPHER_NAME , $ key , OPENSSL_RAW_DATA , base64_decode ($ parts [1 ]));
67+ return $ decryptedData ;
68+ }
69+
70+ }
71+
72+ ?>
0 commit comments