我正在尝试验证从网络服务收到的数据字符串及其RSA-SHA256签名,我完全无法从证书中加载私钥/公钥。
我有以下代码从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());
它输出证书的全部信息:
Version: V3
Subject: EMAILADDRESS=...
...
Algorithm: [SHA256withRSA]
...
但是如果尝试使用以下代码加载和检索私钥:
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);
我收到以下异常
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
keyFactory.generatePublic方法中的。如果将其更改为generatePrivate,则结果相同。
答案 0 :(得分:1)
感谢詹姆斯,按照你的建议我做了以下事情:
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);
答案 1 :(得分:0)
有一个initVerify
that simply takes a certificate。 Internaly它当然只是获取公钥,但通常没有理由你这样做。