Skip to content

Instantly share code, notes, and snippets.

@h1kkan
Created June 24, 2020 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h1kkan/3f08d07f4c89ba659b9522ca721d06c3 to your computer and use it in GitHub Desktop.
Save h1kkan/3f08d07f4c89ba659b9522ca721d06c3 to your computer and use it in GitHub Desktop.
A simple two-way function to encrypt or decrypt a string
/**
* 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;
}
/*
# Example
```
$encrypted = my_simple_crypt( 'Hello World!', 'e' );
```
return value => RTlOMytOZStXdjdHbDZtamNDWFpGdz09
```
$decrypted = my_simple_crypt( 'RTlOMytOZStXdjdHbDZtamNDWFpGdz09', 'd' );
```
return value => Hello World!
*/
@chrisc0
Copy link

chrisc0 commented Jul 13, 2023

Is this function open source?

@h1kkan
Copy link
Author

h1kkan commented Jul 29, 2023

Is this function open source?

might be, but that not my code as header says :)

http://web.archive.org/web/20200513045600/https://nazmulahsan.me/simple-two-way-function-encrypt-decrypt-string/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment