Question

I encrypt/decrypt a message like the following: Encrypt string -> base64 encode bytes -> serialize string -> deserialize string -> decode b64 -> decrypt bytes.

The encryption looks like this:

PublicKey pubKey = readPublicKey();
Cipher cipher;
cipher = Cipher.getInstance(CRYPTO_ALG);
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherData;
cipherData = cipher.doFinal(message.getBytes());
return cipherData;

Decryption is done like so:

PrivateKey pk = readPrivateKey();
Cipher cipher = Cipher.getInstance(CRYPTO_ALG);
cipher.init(Cipher.DECRYPT_MODE, pk);

return new String(cipher.doFinal(data));

The keys are read like this:

ObjectInputStream oin =
   new ObjectInputStream(new BufferedInputStream(is));
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();

RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey privKey = fact.generatePrivate(keySpec);

return privKey;

I have omitted the b64 stuff here, but I have verified that the problem does not affect that code.

What happens now is that I actually get the correct answer, but it is prepended with binary gibberish. If I encrypt "TESTDATA", I will get TESTDATA. The code works fine in plain Java, but fails in Android. Does anyone know how to fix this?

EDIT: Encrypting/decrypting using RSA/NONE/NoPadding does not seem to help. I also use org.bouncycastle in the plain JRE.

Was it helpful?

Solution

In my experience, defaults are a tremendous and never-ending source of hard-to-find bugs in Java crypto. They can bite anybody but they prey on beginners. A beginner is most likely to choose defaults because, by their very nature, they are confused and are looking to simplify. And they are hard to spot, indeed almost invisible, because they are not there. When you look at String.getBytes() it looks completely innocent. Why would a beginner suspect that new String(s.getBytes()) is ever not equal to s? Worst of all, testing seems to indicate it is true. It is only when you transport the byte[] from s.getBytes() to another platform with a different platform default character set that you notice the bug.

Never use String.getBytes(), always use String.getBytes(Charset). Never use the String(byte[]) constructor, always use String(byte [], Charset) constructor. You can always use the UTF-8 charset (Charset.forName("UTF-8")). I use it exclusively.

Similarly, always specify all three components algorithm/mode/padding in the Cipher.getInstance(String) factory method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top