Last active
August 12, 2021 11:49
-
-
Save LudovicOmarini/3b231824416be34d6973670391c4413a to your computer and use it in GitHub Desktop.
How to encrypt/decrypt a string 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
/* | |
.SYNOPSIS | |
Encrypt and decrypt a string. | |
.DESCRIPTION | |
This function is a simple way to encrypt and decrypt a string. | |
.EXAMPLE | |
To encrypt : | |
$encrypted = encryption( 'Hello World!', 'e' ); | |
To decrypt : | |
$decrypted = encryption( 'RTlOMytOZStXdjdHbDZtamNDWFpGdz09', 'd' ); | |
*/ | |
function encryption( $string, $action = 'e' ) { | |
// Change these values to your own | |
$key = 'XXXXXXXXX'; | |
$iv = 'XXXXXXXXXX'; | |
$output = false; | |
$encrypt_method = "AES-256-CBC"; | |
$key = hash( 'sha256', $key ); | |
$iv = substr( hash( 'sha256', $iv ), 0, 16 ); | |
// Encode | |
if( $action == 'e' ) { | |
$output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $iv ) ); | |
} | |
// Decode | |
else if( $action == 'd' ){ | |
$output = openssl_decrypt( base64_decode( $string ), $encrypt_method, $key, 0, $iv ); | |
} | |
return $output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment