Search code examples
javascriptphpcryptojs

CryptoJS AES encrypt (with key size 128 / 8) equivalent in PHP


I am newbie in PHP and I was trying to achieve the CryptoJS AES encryption equivalent in PHP. I saw this post but unfortunately I was not able to achieve the same. I was getting a different output in PHP code as encrypted string.

Where did I go wrong?

Javascript Code

const customerObject = {
  CustomerName: "test",
  EmailID: "tester@test.com",
  Street: "Test",
  City: "London",
  Country: "United Kingdom",
  ZipCode: "XXX XXX",
};

const token = "8056483646328123";

const key = CryptoJS.enc.Utf8.parse(token);
const iv = CryptoJS.enc.Utf8.parse(token);

const returnEncrypted = CryptoJS.AES.encrypt(
  CryptoJS.enc.Utf8.parse(customerObject),
  key,
  {
    iv: iv,
    keySize: 128 / 8,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  }
);

PHP Code

 <?php
    
    $customer = [
       'CustomerName' => "test",
       'EmailID' => "tester@test.com",
       'Street' => "Test",
       'City' => "London",
       'Country' => "United Kingdom",
       'ZipCode' => "XXX XXX",
    ];
    
    
    $plaintext  = json_encode($customer);
    $method     = 'AES-128-CBC';
    
    $key = hex2bin("8056483646328123");
    $iv  = hex2bin("8056483646328123");
    
    $ciphertext = openssl_encrypt(
       $plaintext,
       $method,
       $key,
       OPENSSL_RAW_DATA,
       $iv
    );
    
    
    $ciphertext = base64_encode($ciphertext);

    echo $ciphertext;
    
    ?>

Solution

  • As @Topaco pointed out in comments, the key and IV must not be hex decoded, i.e. remove both hex2bin().

    The corrected code is given below.

    <?php
        
        $customer = [
           'CustomerName' => "test",
           'EmailID' => "tester@test.com",
           'Street' => "Test",
           'City' => "London",
           'Country' => "United Kingdom",
           'ZipCode' => "XXX XXX",
        ];
        
        
        $plaintext  = json_encode($customer);
        $method     = 'AES-128-CBC';
        
        $key = "8056483646328123";
        $iv  = "8056483646328123";
        
        $ciphertext = openssl_encrypt(
           $plaintext,
           $method,
           $key,
           OPENSSL_RAW_DATA,
           $iv
        );
        
        
        $ciphertext = base64_encode($ciphertext);
    
        echo $ciphertext;
        
        ?>