Nava Polak Onik
Nava Polak Onik

Reputation: 1629

Encrypt in java, decrypt in node.js


I need to encrypt in java and decrypt with node.js. The decryption result is corrupted.

Here is the java code:

    public String encrypt(SecretKey key, String message){ 
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");              
        cipher.init(Cipher.ENCRYPT_MODE, key);        
        byte[] stringBytes = message.getBytes("UTF8");       
        byte[] raw = cipher.doFinal(stringBytes);

        // converts to base64 for easier display.
        BASE64Encoder encoder = new BASE64Encoder();
        String base64 = encoder.encode(raw);

        return base64;

    }

Here is the node.js code:

    AEse3SCrypt.decrypt = function(cryptkey,  encryptdata) {
    encryptdata = new Buffer(encryptdata, 'base64').toString('binary');

    var decipher = crypto.createDecipher('aes-128-cbc', cryptkey);
    decipher.setAutoPadding(false);
    var decoded  = decipher.update(encryptdata);

    decoded += decipher.final();
    return decoded;
  }

  As a key I use: "[B@4ec6948c"
  The jave encrypted result is: "dfGiiHZi8wYBnDetNhneBw=="<br>
  The node.js result is garbich....
  1. In java I use "PKCS5Padding". What should be done in node.js regarding padding? I made setAutoPadding(false). If I don't do it I get error decipher fail. (only from node.js version 0.8).
  2. I tried to remove utf8 encoding from the java in order to be complementary with the node.js but it didn't work. Any idea what is wrong?

Upvotes: 2

Views: 2704

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499760

As a key I use: "[B@4ec6948c"

That sounds very much like you're just calling toString() on a byte array. That's not giving you the data within the byte array - it's just the default implementation of Object.toString(), called on a byte array.

Try using Arrays.toString(key) to print out the key.

If you were using that broken key value in the node.js code, it's no wonder it's giving you garbage back.

I tried to remove utf8 encoding from the java in order to be complementary with the node.js

That's absolutely the wrong approach. Instead, you should work out how to make the node.js code interpret the plaintext data as UTF-8 encoded text. Fundamentally, strings are character data and encryption acts on binary data - you need a way to bridge the gap, and UTF-8 is an entirely reasonable way of doing so. The initial result of the decryption in node.js should be binary data, which you then "decode" to text via UTF-8.

I'm afraid I don't know enough about the padding side to comment on that.

Upvotes: 1

Related Questions