Skip to content

Instantly share code, notes, and snippets.

@oropesa
Last active June 10, 2022 16:05
Show Gist options
  • Save oropesa/8709641686bfb565c9f8f1bcf4c24969 to your computer and use it in GitHub Desktop.
Save oropesa/8709641686bfb565c9f8f1bcf4c24969 to your computer and use it in GitHub Desktop.
Encrypt and decrypt in php
$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 );
}
@oropesa
Copy link
Author

oropesa commented Jun 10, 2022

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.

@utsaroy4
Copy link

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