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

Saturday, January 11, 2014

Two aliases for the same MySQL table

Here's how to establish database relationships between connected entities. In this example we'll use a highways map. The final query will show city names and highway that connects them in  result set rows.

Map of highways:

Connections between cities
Connections between cities