Close

PHP: String encryption and decryption

String Encryption

[code language=”php”]
$string = "Some String to encrypted";

$key = "secretscode";
$cipher_alg = MCRYPT_RIJNDAEL_128;
$iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher_alg, MCRYPT_MODE_ECB), MCRYPT_RAND);
$encrypted_string = mcrypt_encrypt($cipher_alg, $key, $string, MCRYPT_MODE_CBC, $iv);

print "Encrypted string: ".bin2hex($encrypted_string)."
";
[/code]

Encrypted string: b7634f7632625ce353d651a771a49c6b308f8c8e7bd2d96a224837f7c65b3ac2

String Decryption

[code language=”php”]
$decrypted_string = mcrypt_decrypt($cipher_alg, $key, $encrypted_string, MCRYPT_MODE_CBC, $iv);

print "Decrypted string: $decrypted_string";
[/code]

Decrypted string: Some String to encrypted