Home > Backend Development > PHP Tutorial > How to Decrypt a Password Encrypted with CryptoJS in PHP?

How to Decrypt a Password Encrypted with CryptoJS in PHP?

DDD
Release: 2024-11-03 16:56:02
Original
976 people have browsed it

How to Decrypt a Password Encrypted with CryptoJS in PHP?

Troubleshooting Decryption with PHP for JavaScript Encryption

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template