Skip to content

Instantly share code, notes, and snippets.

@heyitsnovi
Created July 15, 2018 08:44
Show Gist options
  • Save heyitsnovi/166e227860aee76984bae6754b8617e6 to your computer and use it in GitHub Desktop.
Save heyitsnovi/166e227860aee76984bae6754b8617e6 to your computer and use it in GitHub Desktop.
Encrypt Decrypt using PHP (Openssl)
<?php
//replace it with your own key
$key = 'TVpI8MlRPQcUH0mOyrKKrJgnIcVM9kXb8Ke6XZkJXW7WyHYbUDMYdNMWgq9e';
$encrypted_str = encrypt_string('John Doe is Here');
$decrypted_str = decrypt_string($encrypted_str);
echo "<pre> Encrypted String: ".$encrypted_str."</pre>";
echo "<pre> Decrypted String: ".$decrypted_str."</pre>";
function encrypt_string($str){
global $key;
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($str, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
return base64_encode( $iv.$ciphertext_raw );
}
function decrypt_string($str){
global $key;
$c = base64_decode($str);
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = substr($c, 0, $ivlen);
$ciphertext_raw = substr($c, $ivlen);
return openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment