Home > Article > Backend Development > How to Decrypt AES Encryption in JavaScript with PHP Using mcrypt_decrypt()?
When encrypting user passwords in JavaScript using CryptoJS and attempting to decrypt them using PHP's mcrypt_decrypt() function, discrepancies can arise. This is primarily because mcrypt_decrypt() only uses the key for encryption/decryption, whereas CryptoJS employs a password to derive both the key and IV. To address this issue, it is necessary to obtain the key and IV in the same manner in PHP.
The following PHP function, evpKDF, can be used to derive the key and IV from a password and salt:
<code class="php">function evpKDF($password, $salt, $keySize = 8, $ivSize = 4, $iterations = 1, $hashAlgorithm = "md5") { // ... (Code omitted for brevity) ... }</code>
Once the key and IV have been derived, the encrypted ciphertext can be decrypted using mcrypt_decrypt():
<code class="php">$keyAndIV = evpKDF("Secret Passphrase", hex2bin($saltHex)); $decryptPassword = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $keyAndIV["key"], hex2bin($cipherTextHex), MCRYPT_MODE_CBC, $keyAndIV["iv"]);</code>
If the encrypted ciphertext was formatted using the proprietary OpenSSL format with "Salted__" prefix, you can use the following function to decrypt it:
<code class="php">function decrypt($ciphertext, $password) { // ... (Code omitted for brevity) ... }</code>
By deriving the key and IV in the same way as CryptoJS and using the appropriate decryption method, you can effectively decrypt encrypted passwords from JavaScript in PHP using mcrypt_decrypt().
The above is the detailed content of How to Decrypt AES Encryption in JavaScript with PHP Using mcrypt_decrypt()?. For more information, please follow other related articles on the PHP Chinese website!