Encrypt with Node.js Crypto module and decrypt with Java (in Android app)

Thanks to all of you. your answers and comments pointed me in the right direction, and with some more research I managed to get a working prototype (pasted below).
It turns out that node’s crypto uses MD5 to hash the key, and padding is apparently (got that one with trial and error) done using PKCS7Padding

As for the reasons to do it at all in the first place:
I have an application comprised of three parts:
A. a backend service
B. a third party data store
C. an android app as a client.

The backend service prepares the data and posts it to the third party.
The android app gets and/or updates data in the data store, which the service may act upon.

The need for encryption, is keeping the data private, even from the third party provider.

As for key management – i guess i can have the server create a new key every preconfigured period of time, encrypt it with the old key and post it to the data store for the client to decrypt and start using, but it’s kind of overkill for my needs.

I can also create a key pair and use that to transfer the new symmetric key every once in a while, but that’s even more overkill (not to mention work)

Anywho, this is the code:
Encrypt on Node.js

var crypto = require('crypto')
var cipher = crypto.createCipher('aes-128-ecb','somepassword')
var text = "the big brown fox jumped over the fence"
var crypted = cipher.update(text,'utf-8','hex')
crypted += cipher.final('hex')
//now crypted contains the hex representation of the ciphertext

Decrypt on Java:

public static String decrypt(String seed, String encrypted) throws Exception {
  byte[] keyb = seed.getBytes("UTF-8");
  MessageDigest md = MessageDigest.getInstance("MD5");
  byte[] thedigest = md.digest(keyb);
  SecretKeySpec skey = new SecretKeySpec(thedigest, "AES/ECB/PKCS7Padding");
  Cipher dcipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
  dcipher.init(Cipher.DECRYPT_MODE, skey);

  byte[] clearbyte = dcipher.doFinal(toByte(encrypted));
  return new String(clearbyte);
}

public static byte[] toByte(String hexString) {
  int len = hexString.length()/2;
  byte[] result = new byte[len];
  for (int i = 0; i < len; i++)
    result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
  return result;
}

Leave a Comment