Because
there are no such values at the start of encryption, an IV is used instead. For AES encryption
(Rijndael_128), the IV and the key must be 32 bytes long.
?– Note At http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation, you can learn
more about the various modes of encryption.
The general steps required for encrypting a string are as follows:
1. Create a 32-byte random IV.
2. Convert the IV (which you keep as a hexadecimal string) into a byte array.
3. Encrypt the string using AES encryption by supplying the IV in byte array format.
4. Convert the resulting encrypted data from a byte array into a hexadecimal string.
Decryption follows a similar scheme:
1. Convert the IV (which you keep as a hexadecimal string) into a byte array (the same
with the encryption first step).
2. Convert the string to decrypt into a byte array.
3. Decrypt the binary string from the previous step by supplying the IV in a byte array.
In this example??™s code, you??™ll use AES, but you can modify the code in the SymmetricCrypt
class to use any of the supported encryption algorithms.
Exercise: Implementing the SymmetricCrypt Class
1. Add a new file in the business directory called symmetric_crypt.php with the following code in it:
class SymmetricCrypt
{
// Encryption/decryption key
private static $_msSecretKey = 'From Dusk Till Dawn';
// The initialization vector
private static $_msHexaIv = 'c7098adc8d6128b5d4b4f7b2fe7f7f05';
// Use the Rijndael Encryption Algorithm
private static $_msCipherAlgorithm = MCRYPT_RIJNDAEL_128;
CHAPTER 16 ?– MANAGING CUSTOMER DETAILS 485
/* Function encrypts plain-text string received as parameter
and returns the result in hexadecimal format */
public static function Encrypt($plainString)
{
// Pack SymmetricCrypt::_msHexaIv into a binary string
$binary_iv = pack('H*', self::$_msHexaIv);
// Encrypt $plainString
$binary_encrypted_string = mcrypt_encrypt(
self::$_msCipherAlgorithm,
self::$_msSecretKey,
$plainString,
MCRYPT_MODE_CBC,
$binary_iv);
// Convert $binary_encrypted_string to hexadecimal format
$hexa_encrypted_string = bin2hex($binary_encrypted_string);
return $hexa_encrypted_string;
}
/* Function decrypts hexadecimal string received as parameter
and returns the result in hexadecimal format */
public static function Decrypt($encryptedString)
{
// Pack Symmetric::_msHexaIv into a binary string
$binary_iv = pack('H*', self::$_msHexaIv);
// Convert string in hexadecimal to byte array
$binary_encrypted_string = pack('H*', $encryptedString);
// Decrypt $binary_encrypted_string
$decrypted_string = mcrypt_decrypt(
self::$_msCipherAlgorithm,
self::$_msSecretKey,
$binary_encrypted_string,
MCRYPT_MODE_CBC,
$binary_iv);
return $decrypted_string;
}
}
?>
CHAPTER 16 ?– MANAGING CUSTOMER DETAILS 486
2.
Pages:
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609