Joe Simpson
Joe Simpson

Reputation: 2594

Encrypting and Decrypting data through transport through Java to Node.js

I'm trying to send data from Java (Android) to an Node.js application, except the encryption isn't working and Node.js is not decrypting properly, and I don't really have a clue what I'm doing.

Java:

                    // Encrypt
                    byte[] input = jo.toString().getBytes("UTF-8");

                    MessageDigest md = MessageDigest.getInstance("MD5");
                    byte[] thedigest = md.digest(ENCRYPTION_KEY.getBytes("UTF-8"));
                    SecretKeySpec skc = new SecretKeySpec(thedigest, "AES/ECB/PKCS5Padding");
                    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
                    cipher.init(Cipher.ENCRYPT_MODE, skc);

                    byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
                    int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
                    ctLength += cipher.doFinal(cipherText, ctLength);
                    String query = Base64.encodeToString(cipherText, Base64.DEFAULT);

query is then sent to our server and jo is an JSONObject

And over in Node, I'm doing:

        var decipher = crypto.createDecipher('aes-128-ecb', encryption_key);
        console.log("System: " + new Buffer(fullBuffer, "base64").toString("binary") );

        chunks = []
        chunks.push( decipher.update( new Buffer(fullBuffer, "base64").toString("binary") , 'hex', 'utf-8') );
        chunks.push( decipher.final('utf-8') );
        var txt = chunks.join("");

        console.log("System: " + txt);
        js = JSON.parse(txt);
        console.log("System: " + js);   

And fullBuffer is the received POST data which transfers over correctly

Upvotes: 0

Views: 1090

Answers (1)

tbroberg
tbroberg

Reputation: 635

Encryption and authentication is brutal to debug because any mistake you make results in randomizing the whole output. Suggestions:

  1. Switch to a non-encrypted transform like Base64 or gzip so that you can see what your output looks like.
  2. Try to figure out which half is broken. Capture your server output and decode it with openssl or python. Generate some good input with one of those and stuff it into your client.
  3. CBC is much more secure than ECB.
  4. If none of that helps, step into the low level cipher and decipher and make sure the keys and ciphertexts match exactly in content and length, and squint at the algorithm selection long and hard.

Upvotes: 2

Related Questions