Skip to content

Instantly share code, notes, and snippets.

@afifmakarim
Created July 25, 2021 04:42
Show Gist options
  • Select an option

  • Save afifmakarim/1874eff37be714b34a37de87abcda769 to your computer and use it in GitHub Desktop.

Select an option

Save afifmakarim/1874eff37be714b34a37de87abcda769 to your computer and use it in GitHub Desktop.
aes-128-ecb php and javascript with same result
const cryptojs = require('crypto-js')
const bin2hex = (s) => {
var v, i, f = 0, a = [];
s += '';
f = s.length;
for (i = 0; i < f; i++) {
a[i] = s.charCodeAt(i).toString(16).replace(/^([\da-f])$/, "0$1");
}
return a.join('');
}
const hex2bin = s => s.match(/../g).map(c => String.fromCharCode(parseInt(c, 16))).join``;
const plainText = "123123"; // text to encrypt
const binKey = hex2bin("297796CCB81D2553B07B379D78D87618")
let k = cryptojs.enc.Latin1.parse(binKey);
let cypher = cryptojs.AES.encrypt(plainText, k, {mode: cryptojs.mode.ECB})
cypher = bin2hex(cryptojs.enc.Latin1.stringify(cypher.ciphertext))
console.log(cypher);
// result : 7fab789da8c34387b3b26496d278ba12
$hexKey = "297796CCB81D2553B07B379D78D87618"; // hex key
$plainText = "123456"; // text to encrypt
$key = hex2bin(hexKey);
$encrypt = openssl_encrypt($plainText, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
echo bin2hex($encrypt);
// result : 7fab789da8c34387b3b26496d278ba12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment