John Davidson

encryption - CryptoJS.AES.encrypt PHP equivalent for AES/CBC/PKCS7

0 comments
Message:


I have a problem in encrypting a header signature in php.
I have to create a signature header to comunicate with some API. they provide me the solution trought postman pre-request script with CryptoJS. here is the code:


const url = request.url.split('?')[0]
const subUrl = url.substring(url.indexOf('/'))

const plainSignature = subUrl + '##' + request.method + '#' + pm.collectionVariables.get('api_key')

const encrypted = CryptoJS.AES.encrypt(plainSignature, CryptoJS.enc.Hex.parse(pm.collectionVariables.get('api_key')), {
iv: CryptoJS.enc.Hex.parse('00000000000000000000000000000000'),
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
})

pm.collectionVariables.set('signature', CryptoJS.enc.Hex.stringify(CryptoJS.enc.Base64.parse(encrypted.toString())))

I have to convert it into php code and here is my php code.


public static function encrypt($secretKey, $plainText) {
try {
// Check secret length
if (!static::isKeyLengthValid($secretKey)) {
throw new \InvalidArgumentException("Secret key's length must be 128, 192 or 256 bits");
}
// Get random initialization vector
// $initVector = bin2hex(openssl_random_pseudo_bytes(static::INIT_VECTOR_LENGTH / 2));
$initVector = bin2hex('00000000000000000000000000000000');
$secretKey = hex2bin($secretKey);

// Encrypt input text
$raw = openssl_encrypt(
$plainText,
static::CIPHER,
$secretKey,
OPENSSL_RAW_DATA,
$initVector
);

// Return base64-encoded string: initVector + encrypted result
$result = base64_encode($initVector . $raw);
if ($result === false) {
// Operation failed
return new static($initVector, null, openssl_error_string());
}
// Return successful encoded object
return new static($initVector, $result);
} catch (\Exception $e) {
// Operation failed
return new static(isset($initVector), null, $e->getMessage());
}
}

and this is the cipher method i've used.


const CIPHER = 'AES-128-CBC';

I provide the plaintext to method, but i get error and the output is not same from crypto js and php.
Do you have any advice for me?
Thank you.



My Answer:
' request.method.toUpperCase() request.data request.headers['Content-Type'] request.headers['X-Api-Key'] request.headers['X-Api-Timestamp'] request.headers['X-Api-Nonce']__const secret = 'your_secret_key'__const encryptedSignature = CryptoJS.AES.encrypt(plainSignature, secret).toString()__request.headers['X-Api-Signature'] = encryptedSignature_

_I need to replicate this encryption process in PHP. I have tried using openssl_encrypt with AES-256-CBC and PKCS7 padding, but the result is not the same as the one generated by CryptoJS. Can you provide me with the PHP equivalent code for the encryption process using AES/CBC/PKCS7 padding?_

Rate this post

5 of 5 based on 6230 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us