Home > OS >  Different AES Encrypt in JavaScript and PHP
Different AES Encrypt in JavaScript and PHP

Time:12-15

I want to encrypt a data with PHP. I before used from a javascript code to encrypt.

JavaScript Code:

const SHARED_KEY="XXelkee4v3WjMP81fvjgpNRs2u2cwJ7n3lnJzPt8iVY=";

const ZERO_IV=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];

let data="6104337983063890";

aesEncrypt = async (data) => {
        try{
            let key =  new Uint8Array(this.base64ToArray(SHARED_KEY));
            let aes = new aesJs.ModeOfOperation.cbc(key, ZERO_IV)
            let bData = aesJs.utils.utf8.toBytes(data);
            let encBytes = aes.encrypt(aesJs.padding.pkcs7.pad(bData))
            return this.arrayToHex(encBytes)
        }catch(err) {
            console.error(err)
            return null
        }
    } 

PHP Code:

$sharedSecret=base64_decode('XXelkee4v3WjMP81fvjgpNRs2u2cwJ7n3lnJzPt8iVY=');

$iv = '0000000000000000';

$data="6104337983063890";
            
$output = openssl_encrypt(
    $data,
    'AES-128-CBC',
    $sharedSecret,
    OPENSSL_RAW_DATA,
    $iv
);

$output=bin2hex($output);

Output in two languages is:

JavaScript: 4b685c988d9e166efd0bc5830e926ae0d60111d9dd73d7b4f3c547282994546f (Correct)

PHP: 091da5cf4ffd853e58f5b4f0a07902219ce7ac9647801af5b3e8f755d63b71b4

I need encrypt with PHP that give me same with JavaScript.

CodePudding user response:

You must use aes-256-cbc as algorithm in the PHP code, because the key is 32 bytes large.

Also you have to apply a zero vector as IV in the PHP code, which you can create with:

$iv = hex2bin('00000000000000000000000000000000');

This way, the PHP code provides the same ciphertext as the JavaScript code.


Note that a static IV is insecure. The correct way is to generate a random (non-secret) IV for each encryption and pass this IV along with the ciphertext to the decrypting side (typically concatenated).

  • Related