Question

I have a PrivateKeyEntry entry in my Java KeyStore (.jks) file. I am able to build a KeyStore instance from this .jks file as follows:

KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(keystoreFileInputStream, passwordCharArray);

I am able to extract PrivateKey and PublicKey instances from keystore as follows:

PrivateKey privateKey = (PrivateKey) keystore.getKey(alias, passwordCharArray);
PublicKey publicKey = keystore.getCertificate(alias).getPublicKey();

I encrypt an array of bytes inputBytes as follows:

Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(inputBytes, 0, 128);

I do the reverse and decrypt encryptedBytes as follows:

Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes, 0, 128);

However, the bytes in decryptedBytes are significantly different from the bytes in inputBytes. They should be the same. What have I done wrong?!

If it's important, I created by Java KeyStore file using KeyTool. Specifically, the following command:

keytool -genkey -alias my_alias -keyalg RSA -keystore my_keystore.jks -keysize 1024
Was it helpful?

Solution

I followed @Cruncher's suggestion and tried a different Java KeyStore (.jks) file and it looks like it was indeed an issue with the .jks file I was working against rather than the code.

I created a new .jks file using the keytool -genkey ... command and encrypting/decrypting using the keys contained with returns the expected results.

Thanks all for the pointers. Appreciate it.

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