Aug 3, 2022
0
Level 2
How to convert javascript Encryption into php for laravel application?
I am integrating one bank related apis in which i have to perform one encryption decryption but they provided me some javascript encryption process and i have to apply it in php so this was javascript encryption code
const crypto = require("crypto");
const algorithm = "aes-128-cbc";
const input = "rohansingh";
const keyStr = "UK9EFHDu4k+aU2tY4g/DKw==";
const keyBytes = Buffer.from(keyStr, "base64");
const iv = keyBytes.slice(0, 16);
const hash = crypto.createHash('sha256');
// console.log(iv);
var checksum = hash.update(input);
checksum = hash.digest("hex")
const encCipher = crypto.createCipheriv(algorithm, keyBytes, iv);
var encrypted = encCipher.update(checksum, "utf-8", "base64");
encrypted += encCipher.final("base64");
console.log("Enc base64 Value: " + encrypted);
const finalEncVal = encodeURIComponent(encrypted);
console.log("Enc uri encoded Value: " + finalEncVal);
now for this i have done this
$secret_key = "5fgf5HJ5g27";
$cipher = "AES-128-CBC";
$plaintext = 'rohansingh';
$key = openssl_digest($secret_key, 'SHA256', TRUE);
$ivlen = openssl_cipher_iv_length($cipher);
// print_r($ivlen);exit();
$iv = openssl_random_pseudo_bytes($ivlen);
// binary cipher
$ciphertext_raw = openssl_encrypt(
$plaintext,
$cipher,
$key,
OPENSSL_RAW_DATA,
$iv
);
// or replace OPENSSL_RAW_DATA & $iv with 0 & bin2hex($iv) for hex cipher (eg. for transmission over internet)
// or increase security with hashed cipher; (hex or base64 printable eg. for transmission over internet)
$hmac = hash_hmac('sha256', $ciphertext_raw, $key, true);
$encText = base64_encode($iv . $hmac . $ciphertext_raw);
print_r($encText);
echo "\n\n";
$ciphertext = $encText;
$secret_key = "5fgf5HJ5g27";
$cipher = "AES-128-CBC";
$c = base64_decode($ciphertext);
$key = openssl_digest($secret_key, 'SHA256', TRUE);
$ivlen = openssl_cipher_iv_length($cipher);
$iv = substr($c, 0, $ivlen);
$hmac = substr($c, $ivlen, $sha2len = 32);
$ciphertext_raw = substr($c, $ivlen + $sha2len);
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $ciphertext_raw, $key, true);
if (hash_equals($hmac, $calcmac))
print_r($original_plaintext);
but i am not sure whether it is correct or not also how can i assure myself that whatever i am doing is going in correct direction as i have not done so much encryption so I just wanted some help
Thank You !!!!
Please or to participate in this conversation.