[英]Verifying RSA SHA256 signature fails getting private key from certificate
I'm trying to verify a data string and its RSA-SHA256 signature received from a webservice and I'm completely stuck loading the private/public key from the certificate. 我正在尝试验证从Web服务接收到的数据字符串及其RSA-SHA256签名,并且完全无法从证书中加载私钥/公钥。
I have the following code to retrieve info from the cer file, I think that is in a DER format because it's not in the typical base64 encoded: 我有以下代码从cer文件中检索信息,我认为它是DER格式的,因为它不是典型的base64编码的:
InputStream in = new FileInputStream(path1);
CertificateFactory factory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) factory.generateCertificate(in);
System.out.println(cert.toString());
It outputs the whole info of the certificate: 它输出证书的全部信息:
Version: V3
Subject: EMAILADDRESS=...
...
Algorithm: [SHA256withRSA]
...
but if a try to load and retrieve the private key with the following code: 但是如果尝试使用以下代码加载和检索私钥:
KeyFactory kf = KeyFactory.getInstance("RSA");
X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(encodedKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey bobPubKey = keyFactory.generatePublic(bobPubKeySpec);
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initVerify(bobPubKey);
sig.update(data_received);
sig.verify(signature_received);
I get the following exception 我得到以下异常
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
in the keyFactory.generatePublic method. 在keyFactory.generatePublic方法中。 Same result if a change it to generatePrivate.
如果将其更改为generatePrivate,则结果相同。
Thanks James, following your advise I made it with the following: 感谢James,根据您的建议,我做到了以下几点:
InputStream in = new FileInputStream(System.getProperty("user.dir") + "\\" + certificateName);
CertificateFactory factory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) factory.generateCertificate(in);
PublicKey pubKey = cert.getPublicKey();
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initVerify(pubKey);
sig.update(xmlContent);
return sig.verify(headerSignature);
There is an initVerify
that simply takes a certificate . 有一个
initVerify
只需要一个证书 。 Internaly it will of course just get the public key, but there is generally no reason for you to do so. Internaly它当然会刚刚得到的公开密钥,但一般没有理由对你这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.