I am developing an OSGi plugin (bundle) which performs encryption on Strings. The Strings themselves are encrypted using AES. I am encrypting the AES key with RSA. All works perfectly in my unit tests.
When I deploy the plugin into Karaf (haven't tried any other OSGi containers at present), the result of the encrypted key is a bunch of zero bytes with a final 1-byte. There are no exceptions being thrown. Everything looks normal except that when I go in with the debugger, I discover that the RSA public key cipher is using a key-spec where the value of the public exponent is zero. This obviously makes no sense and it doesn't surprise me that the output is mainly zeroes.
Can anyone suggest why this might be happening?
Adding some code fragments:
public static Cipher createRsaCipher(final boolean keyTypePublic, final int mode, final KeySpec keySpec) throws GeneralSecurityException
{
final KeyFactory kfpri = KeyFactory.getInstance(RSA);
final Cipher result = Cipher.getInstance(RSA);
result.init(mode, keyTypePublic ? kfpri.generatePublic(keySpec) : kfpri.generatePrivate(keySpec));
return result;
}
private static Cipher createPublicKeyEncryptionCipher(final URL key) throws IOException, GeneralSecurityException {
try (InputStream stream = key.openStream()) {
final byte[] encodedKey = readPublicKeyBytes(stream);
final X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedKey);
return CipherFactory.createRsaCipher(true, Cipher.ENCRYPT_MODE, publicKeySpec);
}
}
private static byte[] encrypt(final byte[] source, Cipher cipher) throws GeneralSecurityException {
final int bytes = source.length;
final int outputSize = cipher.getOutputSize(bytes);
final byte[] buffer = new byte[outputSize];
int resultLength = 0;
final int n = cipher.doFinal(source, 0, bytes, buffer, 0);
resultLength += n;
final byte[] result = new byte[resultLength];
System.arraycopy(buffer, 0, result, 0, resultLength);
return result;
}
openssl rsa -in private.pem -pubout -outform DER -out public.der
more private.pem
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEA6LhJ1xCjo2mOMYO3Km5rk+1jpSUgeFLX296apNHgHVb7e9H/
.....etc...........
o6ZYdYg05ubEu+jRQkdudbA/7AXLwYOzGtzhla7ow5QhYcWtJEOwX4U=
-----END RSA PRIVATE KEY-----