In your attempt to decrypt a password encrypted in JavaScript using CryptoJS and decrypt it on the PHP server with mcrypt_decrypt(), you've encountered an issue where the decrypted password is corrupted. This is because the parameters provided to mcrypt_decrypt() are incorrect.
To resolve this issue, you need to understand the differences in how CryptoJS and mcrypt_decrypt() handle encryption. CryptoJS uses the passphrase provided in var encryptedPassword = CryptoJS.AES.encrypt(password, "Secret Passphrase") to generate both the encryption key and the initialization vector (IV) for AES encryption.
On the other hand, mcrypt_decrypt() only uses the passphrase as the encryption key. This means that you need to derive the key and IV in the same way as CryptoJS in order to successfully decrypt the ciphertext in PHP.
The following code demonstrates how to address this issue:
<code class="php">$saltHex = $_POST['salt']; // Received from the JavaScript request $ciphertextHex = $_POST['ciphertext']; // Received from the JavaScript request // Convert salt from hex to binary $salt = hex2bin($saltHex); function evpKDF($password, $salt, $keySize, $ivSize) { $hasher = hash_init('sha256'); hash_update($hasher, $password); hash_update($hasher, $salt); $derivedBytes = hash_final($hasher, TRUE); return array( "key" => substr($derivedBytes, 0, $keySize), "iv" => substr($derivedBytes, $keySize, $ivSize) ); } // Derive key and IV from passphrase and salt $keyAndIV = evpKDF("Secret Passphrase", $salt, 16, 16); // Decrypt ciphertext using mcrypt_decrypt() $decryptPassword = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $keyAndIV["key"], hex2bin($ciphertextHex), MCRYPT_MODE_CBC, $keyAndIV["iv"]);</code>
By deriving the key and IV in the same manner as CryptoJS, you ensure that the decryption process is performed correctly and the decrypted password is accurate.
The above is the detailed content of How to Decrypt a Password Encrypted with CryptoJS in PHP?. For more information, please follow other related articles on the PHP Chinese website!