Different output encryption both CryptoJS and Java Code

后端 未结 3 1553
攒了一身酷
攒了一身酷 2021-01-31 12:10

I need to encrypt certainly string from client-side (JavaScript) and decrypt from server-side (Java), so I found CryptoJS and I write the code with the same params/configuration

3条回答
  •  不要未来只要你来
    2021-01-31 12:49

    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
    

提交回复
热议问题