Last active
June 10, 2022 16:05
-
-
Save oropesa/8709641686bfb565c9f8f1bcf4c24969 to your computer and use it in GitHub Desktop.
Encrypt and decrypt in php
This file contains 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
$string = "Hello World"; | |
$encrypted = oro_encrypt_string( $string ); | |
$decrypted = oro_decrypt_string( $encrypted ); | |
echo $string . '<br />' . $encrypted . '<br />' . $decrypted; | |
function oro_encrypt_string( $string, $key = '', $iv = '', $method = '' ) { | |
$encrypt_method = empty( $method ) ? 'AES-256-CBC' : $method; | |
$secret_key = empty( $key ) ? 'random' : $key; | |
$secret_iv = empty( $iv ) ? 'random' : $iv; | |
// hash | |
$key = hash( 'sha256', $secret_key ); | |
// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning | |
$iv = substr( hash( 'sha256', $secret_iv ), 0, 16 ); | |
return base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $iv ) ); | |
} | |
function oro_decrypt_string( $string, $key = '', $iv = '', $method = '' ) { | |
$encrypt_method = empty( $method ) ? 'AES-256-CBC' : $method; | |
$secret_key = empty( $key ) ? 'random' : $key; | |
$secret_iv = empty( $iv ) ? 'random' : $iv; | |
// hash | |
$key = hash( 'sha256', $secret_key ); | |
// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning | |
$iv = substr( hash( 'sha256', $secret_iv ), 0, 16 ); | |
return openssl_decrypt( base64_decode( $string ), $encrypt_method, $key, 0, $iv ); | |
} |
Yep, this is '4 years ago' code and
mcrypt_encrypt
is obsoleted in PHP 7.1.0.I'm going to update this gist because of to encrypt/decrypt now I use
openssl_encrypt/decrypt
.
Good...Go ahead
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yep, this is '4 years ago' code and
mcrypt_encrypt
is obsoleted in PHP 7.1.0.I'm going to update this gist because of to encrypt/decrypt now I use
openssl_encrypt/decrypt
.