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