& Amp; lt ;? Php -------- first AES-CBC encryption scheme -------- only for understanding with $ ciphermcrypt_module_open (encrypt, MCRYPT_MODE_CBC,); #128-bit 16-byte iv must be 16 bytes $ key1281234567890123456; $...
'; Printf ("128-bit encrypted result: \ n % s \ n", bin2hex ($ cipherText); echo'
'; Echo'
';} // -------- First AES encryption scheme --------?>
Reposted from: Workshop
'; $ Key = '000000'; $ content = 'hello'; $ padkey = pad2Length ($ key, 16); $ cipher = mcrypt_module_open (MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, ''); $ iv_size = mcrypt_enc_get_iv_size ($ cipher); $ iv = mcrypt_create_iv ($ iv_size, MCRYPT_RAND); # automatically generated by IV? Echo 'length of automatically generated iv: '. strlen ($ iv).' bit: '. bin2hex ($ iv ).'
'; If (mcrypt_generic_init ($ cipher, pad2Length ($ key, 16), $ iv )! =-1) {// PHP pads with NULL bytes if $ content is not a multiple of the block size .. $ cipherText = mcrypt_generic ($ cipher, pad2Length ($ content, 16); mcrypt_generic_deinit ($ cipher); mcrypt_module_close ($ cipher); // Display the result in hex. printf ("128-bit encrypted result: \ n % s \ n", bin2hex ($ cipherText); print ("
") ;}// Decrypt $ mw = bin2hex ($ cipherText); $ td = mcrypt_module_open (encrypt,'', MCRYPT_MODE_ECB, ''); if (mcrypt_generic_init ($ td, $ padkey, $ iv )! =-1) {$ p_t = mdecrypt_generic ($ td, hexToStr ($ mw); mcrypt_generic_deinit ($ td); mcrypt_module_close ($ td ); $ p_t = trimEnd ($ p_t); echo 'decryption: '; print ($ p_t); print ("
"); Print (bin2hex ($ p_t); echo'
';} // Add $ text to the length function pad2Length ($ text, $ padlen) in multiples of $ padlen {$ len = strlen ($ text) % $ padlen; $ res = $ text; $ span = $ padlen-$ len; for ($ I = 0; $ I <$ span; $ I ++) {$ res. = chr ($ span) ;}return $ res ;}// remove the extra length after decryption (because the length of block_size is added during encryption) function trimEnd ($ text) {$ len = strlen ($ text); $ c = $ text [$ len-1]; if (ord ($ c) <$ len) {for ($ I = $ len-ord ($ c); $ I <$ len; $ I ++) {if ($ text [$ I]! = $ C) {return $ text;} return substr ($ text, 0, $ len-ord ($ c);} return $ text ;} // Convert the hexadecimal string to the binary string function hexToStr ($ hex) {$ bin = ""; for ($ I = 0; $ I
'; $ Key = '000000'; $ key = pad2Length ($ key, 16); $ iv = 'async'; $ content = 'hello '; $ content = pad2Length ($ content, 16); $ AESed = bin2hex (mcrypt_encrypt (MCRYPT_RIJNDAEL_128, $ key, $ content, MCRYPT_MODE_ECB, $ iv )); # encrypted echo "128-bit encrypted result :". $ AESed.'
'; $ Jiemi = mcrypt_decrypt (MCRYPT_RIJNDAEL_128, $ key, hexToStr ($ AESed), MCRYPT_MODE_ECB, $ iv); # decrypt echo 'decryption:'; echo trimEnd ($ jiemi ); // -------- Third AES encryption solution --------?> # The KEY length is not limited. the IV length must be a multiple of block_size. # if it is MCRYPT_MODE_ECB encryption, the result is related to the KEY. # if it is MCRYPT_MODE_CBC encryption, the result is related to the KEY and IV.