brix / crypto-js

JavaScript library of crypto standards.
Other
15.87k stars 2.39k forks source link

Encryption in PHP and Decrypt in JS #483

Open Shudhanshu-Appnox opened 9 months ago

Shudhanshu-Appnox commented 9 months ago

Hi, there I want to encrypt my MFA Code in PHP and decrypt that code in JS so that on my network only the encrypted data will be shared.

To achieve this I have followed this in my PHP

$pass = '123456';
$method = 'aes128';
$iv = '4f01bede9221586c';
$enc_data = openssl_encrypt('Message', $method, $pass, null, $iv);
echo $enc_data;

And to decrypt the code in the frontend have used

var bytes  = CryptoJS.AES.decrypt('8duGzD85Y2S3bU1h2Hu5ew==', '123456');
var plaintext = bytes.toString(CryptoJS.enc.Utf8);

But I am getting an empty string in response. Also, the same issue has already #135 created but there was no solution for that there. Please can anyone help me on how to resolve this?

happytalkKO commented 9 months ago

any updates?

Purushottam-industrility commented 6 months ago

This solution should work

import CryptoJS from "crypto-js";

var encryptedData ="base64encoded_encrypted_data"; var base64Decoded = atob(encryptedData);

var key = CryptoJS.enc.Utf8.parse("your_key"); var iv = CryptoJS.enc.Utf8.parse("your_iv");

var decryptedData = CryptoJS.AES.decrypt( { ciphertext: CryptoJS.enc.Base64.parse(base64Decoded), }, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, } );

var decryptedText = decryptedData.toString(CryptoJS.enc.Utf8); console.log("decryptedText", decryptedText);

ojongclinton commented 3 months ago

Any one facing this issue, This is what worked for me : React :

export function decryptEncData(encryptedDataWithIv) {
  var Sha256 = CryptoJS.SHA256;
  var Hex = CryptoJS.enc.Hex;
  var Utf8 = CryptoJS.enc.Utf8;
  var Base64 = CryptoJS.enc.Base64;
  var AES = CryptoJS.AES;

  var secret_key = "TheQuickBrownFoxWasJumping";
  var secret_iv = "4f01bede9221586c";

  var key = Sha256(secret_key).toString(Hex).substr(0, 32); 
  var iv = Sha256(secret_iv).toString(Hex).substr(0, 16);

  // Decryption
  var decrypted = AES.decrypt(encryptedDataWithIv, Utf8.parse(key), {
    iv: Utf8.parse(iv),
  }).toString(Utf8);
  console.log(JSON.parse(decrypted)); // test
}

PHP : Laravel

    private $secretKey = 'TheQuickBrownFoxWasJumping';
    private $secretIv = '4f01bede9221586c';
    private $cipher = 'aes-256-cbc';
    public function encryptData($data)
    {
        // Hash the secret key and IV
        $key = substr(hash('sha256', $this->secretKey), 0, 32);
        $iv = substr(hash('sha256', $this->secretIv), 0, 16);

        // Encrypt the data
        $encrypted = openssl_encrypt($data, $this->cipher, $key, 0, $iv);

        // Encode the result in base64
        return $encrypted;
    }