我有一个带有私钥的证书,该证书存储在Windows证书存储区中。如何使用此 key 解密使用OAEP填充的消息?我可以使用BouncycaSTLe提供程序和pfx文件(PKCS12 key 存储库)解密消息,但不能使用Windows存储库(SunMSCAPI)解密消息。

我基本上在使用这段代码

KeyStore keyStore = java.security.KeyStore.getInstance("Windows-MY");
keyStore.load(null, null);
PrivateKey privateKey = (PrivateKey) keyStore.getKey("keyalias", null);

java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

JceKeyTransRecipient jceKeyTransEnvelopedRecipient = new JceKeyTransEnvelopedRecipient(privateKey);
CMSEnvelopedData envelopedData = new CMSEnvelopedData(Base64.getDecoder().decode(encryptedData));
RecipientInformationStore recipientInfos = envelopedData.getRecipientInfos();
RecipientInformation recipient = recipientInfos.getRecipients().iterator().next();
byte[] decrypted = recipient.getContent(jceKeyTransEnvelopedRecipient);

它导致
Caused by: java.security.InvalidKeyException: No installed provider supports this key: sun.security.mscapi.RSAPrivateKey
    at javax.crypto.Cipher.chooseProvider(Cipher.java:892)
    at javax.crypto.Cipher.init(Cipher.java:1248)
    at javax.crypto.Cipher.init(Cipher.java:1185)
    at org.bouncycastle.operator.jcajce.JceAsymmetricKeyUnwrapper.generateUnwrappedKey(JceAsymmetricKeyUnwrapper.java:148)

如果我这样指定提供者:
JceKeyTransRecipient jceKeyTransEnvelopedRecipient = new JceKeyTransEnvelopedRecipient(privateKey).setProvider("SunMSCAPI");

然后我收到错误消息(不支持OAEP)
Caused by: java.security.NoSuchAlgorithmException: No such algorithm: 1.2.840.113549.1.1.7
    at javax.crypto.Cipher.getInstance(Cipher.java:687)
    at javax.crypto.Cipher.getInstance(Cipher.java:595)
    at org.bouncycastle.jcajce.util.NamedJcaJceHelper.createCipher(NamedJcaJceHelper.java:47)
    at org.bouncycastle.operator.jcajce.OperatorHelper.createAsymmetricWrapper(OperatorHelper.java:267)

不久,java不支持OAEP,即使BC支持OAEP,它也不能将其用于“外部”键。如果是这样,还有其他选择吗?

最佳答案

我认为詹姆斯是correct with his comment。即使Windows平台运行,也只是SunMSCAPIdoesn't support OAEPSunMSCAPI不会释放私钥值,因此发生的事情是Java将搜索支持OAEP 私钥对象的任何提供程序,然后找不到任何提供程序。这解释了最初的异常:No installed provider supports this key: sun.security.mscapi.RSAPrivateKey

注意,由于OAEP是even included as required algorithm,因此语句“Java不支持OAEP”显然是错误的。换句话说,没有OAEP,您甚至不能将其称为Java,实际上SunJCE提供程序确实包含对Java的支持,包括对更多散列函数和其他位大小的支持,而不仅仅是1024位和2048位。但是,这确实需要与软件实现兼容的 key 。

关于java - 如何使用SunMSCAPI key 解密RSA-OAEP,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59088372/

10-09 06:10