使用 Cipher 加密数据时出错

Error when encrypting data using Cipher

我有一个问题,希望有人可以帮助我。

我想将 public 密钥(.cer 文件)加载到密钥库中,然后使用该密钥加密一些数据。

密钥似乎已正确加载到密钥库中,因为我可以使用 keystore.getCertificate(alias) 方法查看其内容。

但是,当我尝试使用此密钥加密一段数据时,出现以下错误:

线程异常 "main" java.security.InvalidKeyException:不支持的键类型:空 在 sun.security.mscapi.RSACipher.engineGetKeySize(RSACipher.java:404)

这是我的代码:

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());

我不确定为什么会收到此错误。

我已经设法找出问题所在。基本上,我错误地从密钥库中检索了证书。代码应该是:

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

而不是:

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