This function will provide you a two-way system to encrypt a string or decrypt an encrypted string.
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 |
/** * Encrypt and decrypt * * @author Nazmul Ahsan <n.mukto@gmail.com> * @link http://nazmulahsan.me/simple-two-way-function-encrypt-decrypt-string/ * * @param string $string string to be encrypted/decrypted * @param string $action what to do with this? e for encrypt, d for decrypt */ function my_simple_crypt( $string, $action = 'e' ) { // you may change these values to your own $secret_key = 'my_simple_secret_key'; $secret_iv = 'my_simple_secret_iv'; $output = false; $encrypt_method = "AES-256-CBC"; $key = hash( 'sha256', $secret_key ); $iv = substr( hash( 'sha256', $secret_iv ), 0, 16 ); if( $action == 'e' ) { $output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $iv ) ); } else if( $action == 'd' ){ $output = openssl_decrypt( base64_decode( $string ), $encrypt_method, $key, 0, $iv ); } return $output; } |
So, how to encrypt a string?
Just call this function and pass your string. Additionally set your second parameter to 'e'
(optional). To encrypt Hello World!
, write-
1 |
$encrypted = my_simple_crypt( 'Hello World!', 'e' ); |
It’ll generate a encrypted string RTlOMytOZStXdjdHbDZtamNDWFpGdz09
And, how to decrypt?
Pass your encrypted string to the function and set second parameter to 'd'
.
1 |
$decrypted = my_simple_crypt( 'RTlOMytOZStXdjdHbDZtamNDWFpGdz09', 'd' ); |
WPpeople works mainly on WordPress based projects.
It specializes in developing Plugins, Themes and WP based apps. Well, you can count SEO and maintenance jobs too.
© WPpeople 2021 - Made with &