cgs83
cgs83

Reputation: 11

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.

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:

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. Same result if a change it to generatePrivate.

Upvotes: 0

Views: 6109

Answers (2)

Maarten Bodewes
Maarten Bodewes

Reputation: 94098

There is an initVerify that simply takes a certificate. Internaly it will of course just get the public key, but there is generally no reason for you to do so.

Upvotes: 0

cgs83
cgs83

Reputation: 11

Thanks James, following your advise I made it with the following:

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

Upvotes: 1

Related Questions