Golang:验证 x509 证书是否使用与指定公钥对应的私钥进行签名

Bar*_*oss 6 go x509

我想要验证 X509 证书,以确保它是由与公钥对应的私钥签名的:

var publicKey *rsa.PublicKey = getPublicKey()
var certificate *x509.Certificate = getCertificate()
certificate.CheckSignature(...)
Run Code Online (Sandbox Code Playgroud)

在我看来,该certificate.CheckSignature方法是正确的方法,但我无法弄清楚它需要的参数,并想寻求社区的帮助。

顺便说一句,我能够在java中做同样的事情(在两个相邻的项目上工作)。它看起来像这样:

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);
Run Code Online (Sandbox Code Playgroud)

我很感谢现场的任何提示!P。

Cra*_*row 2

如果我正确理解你想要做什么,那么答案很简单。

您的证书包含公钥。因此,您所需要做的就是将您的公钥与证书中的公钥进行比较。代码如下:

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")
}
Run Code Online (Sandbox Code Playgroud)

更新

刚刚检查了方法的 OpenJDK 实现.verify。看起来可能存在证书不包含公钥而您实际上需要验证签名的情况。本例的 Go 代码如下所示:

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")
}
Run Code Online (Sandbox Code Playgroud)