Search code examples
javaencryptionkeystore

Error when encrypting data using Cipher


I have a problem that I'm hoping someone may be able to help me with.

I want to load a public key (.cer file) into a keystore and then use this key to encrypt some data.

The key appears to be loaded into the keystore correctly because I can view its contents using the keystore.getCertificate(alias) method.

However, when I then attempt to use this key to encrypt a piece of data, I get the following error displayed:

Exception in thread "main" java.security.InvalidKeyException: Unsupported key type: null at sun.security.mscapi.RSACipher.engineGetKeySize(RSACipher.java:404)

Here is my code:

String alias = "alias";

//Create keystore
KeyStore ksName  = KeyStore.getInstance(KeyStore.getDefaultType());

//Make an empty store
ksName.load(null);

// insert .cer file path here
FileInputStream fis = new FileInputStream("C:\\cert\\certificate.cer");
BufferedInputStream bis = new BufferedInputStream(fis);

CertificateFactory cf = CertificateFactory.getInstance("X.509");

while (bis.available() > 0) 
{
    java.security.cert.Certificate cert = cf.generateCertificate(bis);
    ksName.setCertificateEntry(alias, cert);
}          

// retrieve public key from keystore
PublicKey pubKey = (PublicKey) ksName.getKey(alias, null);

String data = "... data to be encrypted ....";
String alg = "RSA/ECB/PKCS1Padding";
Cipher cipher = Cipher.getInstance(alg);
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte encryptedBytes[] = cipher.doFinal(data.getBytes());

I am not sure why I am getting this error.


Solution

  • I've managed to figure out the problem. Basically, I was doing the retrieval of the certificate from the key store incorrectly. The code should have been:

     java.security.cert.Certificate pubCert = ksName.getCertificate(alias); 
    

    Instead of:

     PublicKey pubKey = (PublicKey) ksName.getKey(alias, null);