比较客户端证书在 Go 中的用法
时间:2024-03-27
浏览:483
作者:佚名
在 Go 中使用客户端证书时,需要验证客户机的公共证书,以允许其访问服务器。可以通过自定义 `VerifyPeerCertificate` 函数实现,该函数接收原始证书字节和验证链。此前,使用 `verifiedChains[0][0].Raw` 未能正确获取客户端公共证书。解决方案是使用传递给回调的 `rawCerts` 字节数组,它包含客户端提交的完整证书,而不是仅包含公钥的 `verifiedChains` 字段。转换证书为字符串可以使用 `pem.EncodeToMemory`。
我的用例看起来我知道我的客户的公共证书,并且只想允许它们。我有一个基于 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”中的字符串看起来不像我用来向服务器发送请求的客户端公共证书,它的长度也较短。
解决方案
证书不仅仅是它的公钥。整个x509.Certificate对象代表了客户端提交的证书,公钥字段只是公钥的实际值。
如果您想比较证书的严格相等性,则应使用传递给回调的 rawcerts [][]byte 参数。 verifypeercertificate 的 tls.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))以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
