Learned this some time ago and have been using it for a while now for password encryption.
The first method will encrypt and string. You can encrypt the same thing more than once, and it will product different results each time.
Code:
function encrypt($data, $key) {
$size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($size, MCRYPT_RAND);
$crypt = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_CBC, $iv);
return bin2hex($iv . $crypt);
}
This second method, can decrypt the string or data as long as the same key is used that encrypted the data:
Code:
function decrypt($data, $key) {
$iv = pack("H*", substr($data, 0, 16));
$x = pack("H*", substr($data, 16));
$res = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $x, MCRYPT_MODE_CBC, $iv);
return $res;
}
So if we do this:
Code:
$encrypted = encrypt("Some Text To Encrypt", "3a39!-%8");
$decrypted = decrypt($encrypted, "3a39!-%8");
echo 'Encrypted: '.$encrypted.'<br>';
echo 'Decrypted: '.$decrypted;
we end up with this:
Code:
Encrypted: f2ec23ba6136e698ad6111c202d58d9cd5dfe297b3b901a499b7e61d6d508742
Decrypted: Some Text To Encrypt
Note how the key on encrypt and decrypt is the same. if you provide an invalid key, you get a bunch of invalid characters.
Also, each time you encrypt a string, you will get a unique encryption. Example:
So if we were to run this in a loop like so:
Code:
for ($i = 0; $i < 3; $i++) {
$encrypted = encrypt("Some Text To Encrypt", "3a39!-%8");
$decrypted = decrypt($encrypted, "3a39!-%8");
echo 'Encrypted: '.$encrypted.'<br>';
echo 'Decrypted: '.$decrypted.'<br><br>';
}
We've encrypted it the same way, with the same key, but the encryption comes out differently each time:
Code:
Encrypted: e730d58041e6136b9ec923bfd695fd95b654e48d08b3ab3c4724c473dad8abde
Decrypted: Some Text To Encrypt
Encrypted: 110742f9211e8c64e90d180d93b12d4028186835830502c64e0b2a367e5678c0
Decrypted: Some Text To Encrypt
Encrypted: 10f0c65669409bd6e2ec95a42086c0ff2d21f81404a5709fee63d552e00bb282
Decrypted: Some Text To Encrypt
as long as you provide the same key to decrypt, as you did encryption, you get the same decryption.
Hope this helps