Skip to content

Instantly share code, notes, and snippets.

@aalonzolu
Created January 19, 2018 16:32
Show Gist options
  • Save aalonzolu/69f63b54b6c94b9518c4e057cc88d267 to your computer and use it in GitHub Desktop.
Save aalonzolu/69f63b54b6c94b9518c4e057cc88d267 to your computer and use it in GitHub Desktop.
simple method to encrypt or decrypt a plain text string with php
<?php
/**
* simple method to encrypt or decrypt a plain text string
* initialization vector(IV) has to be the same when encrypting and decrypting
*
* @param string $action: can be 'encrypt' or 'decrypt'
* @param string $string: string to encrypt or decrypt
*
* @return string
*/
function encrypt_decrypt($action, $string,$secret_key = "supersecret_key") {
$output = false;
$encrypt_method = "AES-256-CBC";
$secret_iv = 'randomString#12231'; // change this to one more secure
$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);
if ( $action == 'encrypt' ) {
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);
} else if( $action == 'decrypt' ) {
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}
return $output;
}
// dinamic string
$dynamic_string = "TOKEN_GEDUCAR#".date("Y-m-d H");
$secret_key = "847EJDALQIS2PE3UDKA7128409EJA"; // same in the connected applications
echo "<pre>";
echo "String Token:". $dynamic_string."\n";
// encrypt string
$encrypted_string = encrypt_decrypt('encrypt',$dynamic_string,$secret_key);
echo "Encrypted String:". $encrypted_string."\n";
//decrypt string
$decrypted_string = encrypt_decrypt('decrypt',$encrypted_string,$secret_key);
echo "Decrypted string:". $decrypted_string."\n";
// al final comparar el string desencriptado con el string dinamico
if($dynamic_string==$decrypted_string){
echo "Correct authentication\n";
}
echo "</pre>";
@luisdatec
Copy link

Hello, I did that code, but the server never decrypt, looks a persist problem. Should I install something ?

The error that shows is: "error:0607A082:digital envelope routines:EVP_CIPHER_CTX_set_key_length:invalid key length"

Any solution ?

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