PHP AES Algorithm
- function Aes128cbcencrypt ($key, $text)
- {
- /**
- * Open the cipher
- */
- $TD = Mcrypt_module_open (mcrypt_rijndael_128, ', MCRYPT_MODE_CBC, ');
- if (! $td)
- {
- throw new Generalsecurityexception (' Invalid mcrypt cipher, check your Libmcrypt library and Php-mcrypt extention ');
- }
- Replaced Mcrypt_dev_random with Mcrypt_rand since Windows doesn ' t have/dev/rand:)
- Srand (Double) microtime () * 1000000);
- $iv = Mcrypt_create_iv (Mcrypt_enc_get_iv_size ($TD), Mcrypt_rand);
- /**
- * Intialize Encryption
- */
- Mcrypt_generic_init ($TD, $key, $IV);
- /**
- * Encrypt Data
- */
- $encrypted = Mcrypt_generic ($TD, $text);
- /**
- * Terminate Encryption Handler
- */
- Mcrypt_generic_deinit ($TD);
- /**
- * AES-128-CBC encryption. The IV is returned as the first bytes
- * of the cipher text.
- */
- Return $IV. $encrypted;
- }
- function Aes128cbcdecrypt ($key, $encrypted _text)
- {
- /**
- * Open the cipher
- */
- $TD = Mcrypt_module_open (mcrypt_rijndael_128, ', MCRYPT_MODE_CBC, ');
- if (is_callable (' mb_substr '))
- {
- $iv = Mb_substr ($encrypted _text, 0, crypto_cipher_block_size, ' latin1 ');
- }
- Else
- {
- $iv = substr ($encrypted _text, 0, crypto_cipher_block_size);
- }
- /**
- * Initialize encryption module for decryption
- */
- Mcrypt_generic_init ($TD, $key, $IV);
- /**
- * Decrypt Encrypted string
- */
- if (is_callable (' mb_substr '))
- {
- $encrypted = Mb_substr ($encrypted _text, Crypto_cipher_block_size, Mb_strlen ($encrypted _text, ' latin1 '), ' latin1 ');
- }
- Else
- {
- $encrypted = substr ($encrypted _text, crypto_cipher_block_size);
- }
- $decrypted = Mdecrypt_generic ($TD, $encrypted);
- /**
- * Terminate decryption handle and close module
- */
- Mcrypt_generic_deinit ($TD);
- Mcrypt_module_close ($TD);
- /**
- * Show String
- */
- Return trim ($decrypted);
- }
- Define (' Crypto_cipher_block_size ', 16);
- $a = aes128cbcencrypt (' Pass ', ' This is Text ');
- echo Base64_encode ($a). "/r/n";
- $b = Aes128cbcdecrypt (' Pass ', $a);
- Echo $b. "/r/n";
- $c = Aes128cbcdecrypt (' Pass ', Base64_decode (Base64_encode ($a)));
- Echo $c. "/r/n";
- ?>
Copy Code |