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.