Different output encryption both CryptoJS and Java Code

后端 未结 3 1509
攒了一身酷
攒了一身酷 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:45

    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");
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-31 13:01

    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.

    0 讨论(0)
提交回复
热议问题