Home >Backend Development >PHP Tutorial >How to Decrypt JavaScript CryptoJS AES Encrypted Data in PHP?

How to Decrypt JavaScript CryptoJS AES Encrypted Data in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 11:09:31280browse

How to Decrypt JavaScript CryptoJS AES Encrypted Data in PHP?

Encryption in JavaScript and Decryption in PHP

Issue

A user is encrypting a password in JavaScript using CryptoJS AES encryption and attempting to decrypt it in PHP using mcrypt_decrypt() but encountering incorrect results.

Solution

The discrepancy arises from the method used to derive the encryption key and initialization vector (IV) in JavaScript and PHP. CryptoJS derives these values using a password, while PHP's mcrypt_decrypt() only expects a key.

PHP Decryption Implementation

To correctly decrypt the ciphertext, the PHP code must derive the encryption key and IV from the password and salt in the same manner as the JavaScript code. This can be achieved using a function like evpKDF(), which implements the hash-based key derivation function (HKDF).

<code class="php">function evpKDF($password, $salt, $keySize = 8, $ivSize = 4, $iterations = 1, $hashAlgorithm = "md5") {
    // ... Implementation ...
}</code>

Once the key and IV are derived, mcrypt_decrypt() can be invoked as follows:

<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>

Alternative Implementation using OpenSSL

Alternatively, the OpenSSL extension can be used to decrypt the ciphertext:

<code class="php">function decrypt($ciphertext, $password) {
    $ciphertext = base64_decode($ciphertext);
    if (substr($ciphertext, 0, 8) != "Salted__") {
        return false;
    }
    $salt = substr($ciphertext, 8, 8);
    $keyAndIV = evpKDF($password, $salt);
    $decryptPassword = openssl_decrypt(
            substr($ciphertext, 16), 
            "aes-256-cbc",
            $keyAndIV["key"], 
            OPENSSL_RAW_DATA, // base64 was already decoded
            $keyAndIV["iv"]);

    return $decryptPassword;
}</code>

The above is the detailed content of How to Decrypt JavaScript CryptoJS AES Encrypted Data in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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