Created
December 21, 2021 01:23
-
-
Save helloworldlab/9d3ce362403143a32243de356446cc0b to your computer and use it in GitHub Desktop.
Encyption/Decryption
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| const CIPHER_METHOD = 'AES-256-CBC'; | |
| const KEY = 'nHPOlI32ncspmDNGnNfOFUh1SI+yLCqW6MznKltCDPI='; | |
| function encrypt($data) | |
| { | |
| // Get key | |
| $key = KEY; | |
| // Append more character if key length below 32 characters | |
| if (strlen($key) != 32) { | |
| $key = str_pad($key, 32, '*'); | |
| } | |
| // Initialization vector length | |
| $iv_length = openssl_cipher_iv_length(CIPHER_METHOD); | |
| $iv = openssl_random_pseudo_bytes($iv_length); | |
| // Encrypt | |
| $ciphertext = openssl_encrypt($data, CIPHER_METHOD, $key, OPENSSL_RAW_DATA, $iv); | |
| // Return $iv at front of string, need it for decoding | |
| $message = $iv . $ciphertext; | |
| // Return encrypted text | |
| return base64_encode($message); | |
| } | |
| function decrypt($data) | |
| { | |
| // Get key | |
| $key = KEY; | |
| // Append more character if key length below 32 characters | |
| if (strlen($key) != 32) { | |
| $key = str_pad($key, 32, '*'); | |
| } | |
| // Base64 decode before decrypting | |
| $iv_with_ciphertext = base64_decode($data); | |
| // Separate initialization vector and encrypted string | |
| $iv_length = openssl_cipher_iv_length(CIPHER_METHOD); | |
| // Get initialization length | |
| $iv = substr($iv_with_ciphertext, 0, $iv_length); | |
| // Get message | |
| $ciphertext = substr($iv_with_ciphertext, $iv_length); | |
| // Decrypt | |
| $decrypted = openssl_decrypt($ciphertext, CIPHER_METHOD, $key, OPENSSL_RAW_DATA, $iv); | |
| // Return decrypted text | |
| return $decrypted; | |
| } | |
| var_dump( | |
| encrypt('Hello World') | |
| ); | |
| var_dump( | |
| decrypt('BFppMLatuNwaMtLB5vMIS5jpcInewDPnL8+iMdyQgz4=') | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment