Different output encryption both CryptoJS and Java Code

我只是一个虾纸丫 提交于 2019-12-02 18:16:33

The problem here is that your key input in inconsistent.

  • CryptoJS.enc.Hex.parse('0123456789abcdef') reads the input as a series of bytes expressed as two-digit hex values: 01, 23, 45, etc.

  • Your Java array specifies byte values using the character-encoding values of the characters. So, the sequence of bytes (in hex) is: 30 (decimal 48, ASCII code for '0'), then 31 (decimal 49, ASCII code for '1'), etc.

You can make the JavaScript conform to the the Java implementation by using CryptoJS.enc.Latin1.parse which will read in the individual character values and use them as byte values: http://jsfiddle.net/gCHAG/1/ (this produces the same j6dSm... output)

However, you probably want each digit to be its own byte. To do that, you need to change both implementations.

Java:

// use hex literals, not characters
byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
// array values: 0x00, 0x01, 0x02, etc

JavaScript:

// remember each bytes is two digits wide
CryptoJS.enc.Hex.parse('000102030405060708090a0b0c0d0e0f')
// array values: 0x00, 0x01, 0x02, etc

The character '0' is not the same as hex value 0. The CryptoJS key is most likely different than the Java key because you're instantiating them as different object types. Print out the keys/IV in both languages after creating them and compare.

EDIT: That said, this will probably be moved to StackOverflow, as questions about specific crypto libraries are not on-topic here.

Very usefull example SoldierCorp, thank you!

Few things to improve your example:

  • Method padString does not support UTF8 and instead of fixing this method lets delete it and use a standard padding

in javascript replace on

padding: CryptoJS.pad.Pkcs7

in java replace on

algorithm = "AES/CBC/PKCS5Padding"
  • Generate key from any string phrase (for IV can be the same)

in javascript replace on

var key = CryptoJS.MD5("Secret Passphrase");

in java replace on

byte[] keyValue = org.apache.commons.codec.digest.DigestUtils.md5("Secret Passphrase");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!