ricmoo / aes-js

A pure JavaScript implementation of the AES block cipher and all common modes of operation for node.js or web browsers.
MIT License
1.45k stars 272 forks source link

need php/openssl advice #86

Closed kernelk closed 5 years ago

kernelk commented 5 years ago

Hi, can someone help me figure out what I am doing wrong? I am trying to get aes-js and php/openssl to communicate. I noticed that using the same key and iv that php/openssl encryption result is larger. This same php/openssl code works with my .NET app. Anyone know what I need to do to make this work?

ClearText: "0123456789abcdef"

keyBase64: 3FotElh1MRwMU/jL7ztLYsqyDlh3J4KkwAJCvLb8py0= ivBase64: 6uiiAZqD1HXowe/QX/Sd1w==

aes-js: resultBase64: 9SeqmlYFXVeMB+8LuCSdiw== php/openssl: resultBase64: 9SeqmlYFXVeMB+8LuCSdiz+Tu/mJVaMN6p0x9BwmpAQ=

///--- JS --- var key = GetRandomBytes(32); //Base64: 3FotElh1MRwMU/jL7ztLYsqyDlh3J4KkwAJCvLb8py0= var iv = GetRandomBytes(16); //Base64: 6uiiAZqD1HXowe/QX/Sd1w==

var aesCbc = new aesjs.ModeOfOperation.cbc(key, iv);

var clearText = "0123456789abcdef"; var clearBytes = aesjs.utils.utf8.toBytes(clearText);

//padding omitted for this test, already 16 bytes var encrypted = aesCbc.encrypt(clearBytes); // resulted in Base64: 9SeqmlYFXVeMB+8LuCSdiw==

// test decryption aesCbc = new aesjs.ModeOfOperation.cbc(key, iv); // need new instance var decrypted = aesjs.utils.utf8.fromBytes(aesCbc.decrypt(encrypted)); // this works

///--- PHP 7 --- // trying to decrypt encrypted from aes-js fails using this: $decrypted = openssl_decrypt($encrypted, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv); // fails

$encrypted = openssl_encrypt("0123456789abcdef", 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);

// reulted in Base64: 9SeqmlYFXVeMB+8LuCSdiz+Tu/mJVaMN6p0x9BwmpAQ= // aes-js fails to decrypt this

kernelk commented 5 years ago

Nevermind on this, CryptoJS worked in 1 line and no padding to deal with. Thanks.