2

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.

2
  • I was created/modifed my gist on GitHub based on this answer. I hope that it is work for you. Commented Dec 15, 2021 at 2:50
  • Just a reminder, even if you encrypt data in JS, the code will still display the secret and such., which could be a security risk in future. Commented Dec 15, 2021 at 3:19

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.