In JavaScript, an encrypted user password is being created using CryptoJS, utilizing password-based key derivation for both the key and IV. However, decryption attempts on the PHP server, employing the mcrypt library, have failed, resulting in nonsensical decrypted strings.
The primary error stems from the differing encryption methods employed in JavaScript (CryptoJS) and PHP (mcrypt). In CryptoJS, key and IV are derived from the password, while mcrypt relies solely on the password for encryption/decryption. To rectify this, the key and IV must be generated in PHP using a technique similar to that used in CryptoJS.
Transferring the saltHex and cipherTextHex parameters to the PHP server, an enhanced JavaScript encryption process is now implemented:
<code class="javascript">var encryptedPassword = CryptoJS.AES.encrypt(password, "Secret Passphrase"); var ivHex = encryptedPassword.iv.toString(); var saltHex = encryptedPassword.salt.toString(); var cipherTextHex = encryptedPassword.ciphertext.toString();</code>
The following PHP function derives key and IV from a password and salt:
<code class="php">function evpKDF($password, $salt, $keySize = 8, $ivSize = 4, $iterations = 1, $hashAlgorithm = "md5") { /* ... code for key and IV derivation ... */ return [ "key" => substr($derivedBytes, 0, $keySize * 4), "iv" => substr($derivedBytes, $keySize * 4, $ivSize * 4) ]; }</code>
Armed with the derived key and IV, decryption is performed in PHP:
<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>
Using the OpenSSL extension is an alternative for decryption:
<code class="php">$decryptPassword = openssl_decrypt( substr($ciphertext, 16), "aes-256-cbc", $keyAndIV["key"], OPENSSL_RAW_DATA, $keyAndIV["iv"]);</code>
With these modifications, seamless encryption and decryption of the user password are now achievable between JavaScript and PHP, ensuring secure data handling.
The above is the detailed content of How to Decrypt CryptoJS Encrypted Passwords in PHP Using mcrypt?. For more information, please follow other related articles on the PHP Chinese website!