Skip to content

Instantly share code, notes, and snippets.

@iprodev
Last active December 14, 2018 19:43
Show Gist options
  • Save iprodev/7cfe9d51a840d3449364f8f77bf4cd4e to your computer and use it in GitHub Desktop.
Save iprodev/7cfe9d51a840d3449364f8f77bf4cd4e to your computer and use it in GitHub Desktop.
PHP : Powerful encrypt and decrypt using OpenSSL
<?php
/**
* Powerful 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 = 'This is my secret key';
$cipher = "AES-256-CBC";
$ivlen = openssl_cipher_iv_length( $cipher );
if ( $action == 'encrypt' ) {
$iv = openssl_random_pseudo_bytes( $ivlen );
$ciphertext_raw = openssl_encrypt( $string, $cipher, $secret_key, $options = OPENSSL_RAW_DATA, $iv );
$hmac = hash_hmac( 'sha512', $ciphertext_raw, $secret_key, $as_binary = true );
$ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );
return $ciphertext;
} else if( $action == 'decrypt' ) {
$c = base64_decode( $string );
$iv = substr( $c, 0, $ivlen );
$hmac = substr( $c, $ivlen, $sha2len = 64 );
$ciphertext_raw = substr( $c, $ivlen+$sha2len );
$original_plaintext = openssl_decrypt( $ciphertext_raw, $cipher, $secret_key, $options = OPENSSL_RAW_DATA, $iv );
$calcmac = hash_hmac( 'sha512', $ciphertext_raw, $secret_key, $as_binary = true );
//PHP 5.6+ timing attack safe comparison
if ( hash_equals( $hmac, $calcmac ) )
return $original_plaintext;
else
false;
}
}
$plain_txt = "This is my plain text";
echo "Plain Text = " .$plain_txt. "\n";
$encrypted_txt = encrypt_decrypt( 'encrypt', $plain_txt );
echo "Encrypted Text = " .$encrypted_txt. "\n";
$decrypted_txt = encrypt_decrypt( 'decrypt', $encrypted_txt );
echo "Decrypted Text =" .$decrypted_txt. "\n";
if ( $plain_txt === $decrypted_txt ) echo "SUCCESS";
else echo "FAILED";
echo "\n";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment