Search code examples
gox509

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.


Solution

  • 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")
    }