简体   繁体   中英

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

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.

If I properly understood what you are trying to do, then answer is simple.

Your certificate includes the public key. So all you need is to compare your public key with the public key from the certificate. The code looks like:

if certificate.PublicKey.(*rsa.PublicKey).N.Cmp(publicKey.(*rsa.PublicKey).N) == 0 && publicKey.(*rsa.PublicKey).E == certificate.PublicKey.(*rsa.PublicKey).E {
    println("Same key")
} else {
    println("Different keys")
}

Update

Just checked OpenJDK implementation of .verify method . Looks like there can be situation when certificate doesn't contain the public key and you actually need to verify signature. The Go code for this case looks like this:

h := sha256.New()
h.Write(certificate.RawTBSCertificate)
hash_data := h.Sum(nil)

err = rsa.VerifyPKCS1v15(publicKey.(*rsa.PublicKey), crypto.SHA256, hash_data, certificate.Signature)
if err != nil {
    println("Signature does not match")
}

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM