Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: verify x509 certificate was signed using private key that corresponds to the specified public key

Tags:

go

x509

I want to get an X509 certificate verified to make sure it was signed by the private key that corresponds to the public key:

var publicKey *rsa.PublicKey = getPublicKey()
var certificate *x509.Certificate = getCertificate()
certificate.CheckSignature(...)

It seems to me that certificate.CheckSignature method is the right way to go but I can not figure out the parameters it needs and would like to ask for community's help.

Btw, I was able to do the same in java (working on two adjacent projects). It looks like this:

RSAPublicKey publicKey = getPublicKey();
X509Certificate certificate = X509CertUtils.parse(...);

// Verifies that this certificate was signed using the
// private key that corresponds to the specified public key.
certificate.verify(publicKey);

I appreciate any hints on the field! P.

like image 834
Barbadoss Avatar asked Mar 02 '17 15:03

Barbadoss


1 Answers

Thanks Roman, I've managed to get it working like this:

hash := sha1.New()
hash.Write(certificate.RawTBSCertificate)
hashData := hash.Sum(nil)
rsa.VerifyPKCS1v15(dsPublicKey, crypto.SHA1, hashData, certificate.Signature)

So, that's basically what you recommended but with the use of sha1 hash instead - this is what I get for the certificate I generated locally. I've also managed to get it working by temporary swapping certificate's public key with the key I would like to verify against:

certificate.PublicKey = certificateAuthorityPublicKey
certificate.CheckSignature(x509.SHA1WithRSA, certificate.RawTBSCertificate, certificate.Signature) 

The second approach looks hack-ish of course but both of them work as expected...

Wonder if it is possible to figure out whether it is SHA1 or SHA256 at runtime?

like image 104
Barbadoss Avatar answered Oct 31 '22 12:10

Barbadoss