比较客户端证书

compare client certificates in go

我的用例看起来我知道我客户的 public 证书并且只想允许它们。我有一个基于 gin 的 go 服务器和一个 TLS 配置,我在其中为 属性 "VerifyPeerCertificate" 分配了一个方法。 函数看起来像

func customVerifyPeerCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {

if len(verifiedChains) < 1 {
    return errors.New("Verified certificate chains is empty.")
}
if len(verifiedChains[0]) < 1 {
    return errors.New("No certificates in certificate chains.")
}
if len(verifiedChains[0][0].Subject.CommonName) < 1 {
    return errors.New("Common name can not be empty.")
}

fmt.Println(verifiedChains[0][0].Raw)

publicKeyDer, _ := x509.MarshalPKIXPublicKey(verifiedChains[0][0].PublicKey)

publicKeyBlock := pem.Block{
    Type:  "CERTIFICATE",
    Bytes: publicKeyDer,
}
publicKeyPem := string(pem.EncodeToMemory(&publicKeyBlock))
}

然而,问题是变量"publicKeyPem"中的字符串看起来不像我用来向服务器发送请求的客户端public证书,它的长度也更短。

证书不仅仅是它的 public 密钥。整个x509.Certificate对象代表客户端出示的证书,public键字段只是public键的实际值。

如果要比较证书的严格相等性,应使用传递给回调的 rawCerts [][]byte 参数。 VerifyPeerCertificatetls.Config 评论中提到了这一点:

    VerifyPeerCertificate, if not nil, is called after normal
    certificate verification by either a TLS client or server. It
    receives the raw ASN.1 certificates provided by the peer and also
    any verified chains that normal processing found. If it returns a
    non-nil error, the handshake is aborted and that error results.

感谢 Marc,我知道我使用了错误的变量。要将证书转换为客户端使用的字符串,请使用以下代码

publicKeyBlock := pem.Block{
  Type:  "CERTIFICATE",
  Bytes: rawCerts[0],
}
publicKeyPem := string(pem.EncodeToMemory(&publicKeyBlock))