Saturday, January 18, 2014

Two Way Encryption

Two way encryption on PHP works with mcrypt extension enabled.
Here's a simple snippet that uses password and generates different encryption string every time you reload.
<?php
$string = "This is a string to be encrypted";
$key = "This is a key";
// Encryption Algorithm
$alg = MCRYPT_TWO_FISH;
// Create the initialization vector for added security
$iv = mcrypt_create_iv(mcrypt_get_iv_size($alg, MCRYPT_MODE_ECB), MCRYPT_RAND);
// Output original string
print "Original string: $string <p>";
// Encrypt $string
$encrypted_string = mcrypt_encrypt($alg, $key, $string, MCRYPT_MODE_CBC, $iv);
// Convert to hexadecimal and output to browser
print "Encrypted string: ".bin2hex($encrypted_string)."<p>";
$decrypted_string = mcrypt_decrypt($alg, $key, $encrypted_string, MCRYPT_MODE_CBC, $iv);

print "Decrypted string: $decrypted_string";
?>
A short video how code works

No comments:

Post a Comment