在 go 中比较客户端证书

我的用例看起来像我知道客户的公共证书并且只想允许它们。我有一个基于 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”中的字符串看起来不像我用来向服务器发送请求的客户端公共证书,它的长度也较短。


慕田峪7331174
浏览 101回答 2
2回答

繁花不似锦

证书不仅仅是它的公钥。整个x509.Certificate对象代表了客户端提交的证书,公钥字段只是公钥的实际值。如果您想比较证书的严格相等性,您应该使用rawCerts [][]byte传递给回调的参数。这在tls.Config注释中提到VerifyPeerCertificate: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.

陪伴而非守候

我知道我使用了错误的变量。要将证书转换为客户端使用的字符串,请使用以下代码publicKeyBlock := pem.Block{&nbsp; Type:&nbsp; "CERTIFICATE",&nbsp; Bytes: rawCerts[0],}publicKeyPem := string(pem.EncodeToMemory(&publicKeyBlock))
打开App,查看更多内容
随时随地看视频慕课网APP