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.