关于Java:验证RSA Sa256签名无法从证书中获取私钥

Verifying RSA SHA256 signature fails getting private key from certificate

我正在尝试验证从Web服务接收到的数据字符串及其RSA-SHA256签名,我完全无法从证书加载私钥/公钥。

我有以下代码从CER文件中检索信息,我认为这是一种der格式,因为它不在典型的base64编码中:

1
2
3
4
InputStream in = new FileInputStream(path1);
CertificateFactory factory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) factory.generateCertificate(in);
System.out.println(cert.toString());

它输出证书的全部信息:

1
2
3
4
5
Version: V3
Subject: EMAILADDRESS=...
...
Algorithm: [SHA256withRSA]
...

但是,如果尝试使用以下代码加载和检索私钥:

1
2
3
4
5
6
7
8
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);

我得到以下例外

1
 java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format

在keyFactory.generatepublic方法中。如果把它改为generateprivate,结果也是一样的。


谢谢詹姆斯,按照你的建议,我做了如下:

1
2
3
4
5
6
7
8
9
10
11
        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);

有一个initVerify只需要一个证书。当然,从内部来说,它只会获取公钥,但通常没有理由这样做。