Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Looking for a way to encrypt data (mainly strings) in node and decrypt in an android app (java).

Have successfully done so in each one (encrypt/decrypt in node, and encrypt/decrypt in java) but can't seem to get it to work between them.

Possibly I'm not encrypting/decrypting in the same way, but each library in each language has different names for same things...

Any help appreciated.

here's some code: Node.js

var crypto = require('crypto')
var cipher = crypto.createCipher('aes-128-cbc','somepass')
var text = "uncle had a little farm"
var crypted = cipher.update(text,'utf8','hex')
crypted += cipher.final('hex')
//now crypted contains the hex representation of the ciphertext

and java

private static String decrypt(byte[] raw, byte[] encrypted) throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec );
    byte[] decrypted = cipher.doFinal(encrypted);
    return new String(decrypted);
}

the raw key is created like this

private static byte[] getRawKey(String seed) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    byte[] seedBytes = seed.getBytes()
    sr.setSeed(seedBytes);
    kgen.init(128, sr); // 192 and 256 bits may not be available
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    return raw;
}

while the encrypted hex string is converted to bytes like this

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;
}
like image 596
Shh Avatar asked Oct 16 '11 22:10

Shh


2 Answers

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;
}
like image 126
Shh Avatar answered Oct 13 '22 21:10

Shh


Apparently if you pass a passphrase to crypto.createCipher() it uses OpenSSL's EVP_BytesToKey() to derive the key. You can either pass a raw byte buffer and use the same to initialize Java's SecretKey, or emulate EVP_BytesToKey() in your Java code. Use $ man EVP_BytesToKey for more details, but essentially it hashes the passphrase multiple times with MD5 and concatenates a salt.

As for using a raw key, something like this should let you use a raw key:

var c = crypto.createCipheriv("aes-128-ecb", new Buffer("00010203050607080a0b0c0d0f101112", "hex").toString("binary"), "");

Note that since you are using CBC, you need to use the same IV for encryption and decryption (you might want to append it to your message, etc.)

Mandatory warning: implementing a crypto protocol yourself is rarely a good idea. Even if you get this to work, are you going to use the same key for all messages? For how long? If you decide to rotate the key, how to you manage this. Etc, .etc.

like image 38
Nikolay Elenkov Avatar answered Oct 13 '22 23:10

Nikolay Elenkov