Skip to content

Instantly share code, notes, and snippets.

@LudovicOmarini
Last active August 12, 2021 11:49
Show Gist options
  • Save LudovicOmarini/3b231824416be34d6973670391c4413a to your computer and use it in GitHub Desktop.
Save LudovicOmarini/3b231824416be34d6973670391c4413a to your computer and use it in GitHub Desktop.
How to encrypt/decrypt a string in PHP.
/*
.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