如何解析自定义X509v3扩展在golang?



我有一个client.crt.pem。

我想获得自定义扩展key-value。

(例如

2.9.1.6.2.6.1.9.9.4.1G1

2.9.1.6.2.6.1.9.9.4.10C024731

)。

如何在golang中解析它们?

这是证书信息。

openssl x509 -in client.crt.pem -noout -text显示

...
...
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
Netscape Cert Type:
SSL Client, S/MIME
Netscape Comment:
OpenSSL Generated Client Certificate
X509v3 Key Usage: critical
Digital Signature, Non Repudiation, Key Encipherment
X509v3 Extended Key Usage:
TLS Web Client Authentication, E-mail Protection
2.9.1.6.2.6.1.9.9.4.1:
..G1
2.9.1.6.2.6.1.9.9.4.2:
..R1
2.9.1.6.2.6.1.9.9.4.3:
..3
X509v3 Subject Alternative Name:
IP Address:127.0.0.1, IP Address:0:0:0:0:0:0:0:1, DNS:localhost
...
...

或者使用openssl asn1parse -i -in client.crt.pem

...
...
998:d=4  hl=2 l=  18 cons:     SEQUENCE
1000:d=5  hl=2 l=  10 prim:      OBJECT            :2.9.1.6.2.6.1.9.9.4.1
1012:d=5  hl=2 l=   4 prim:      OCTET STRING      [HEX DUMP]:0C024731
1018:d=4  hl=2 l=  18 cons:     SEQUENCE
1020:d=5  hl=2 l=  10 prim:      OBJECT            :2.9.1.6.2.6.1.9.9.4.2
1032:d=5  hl=2 l=   4 prim:      OCTET STRING      [HEX DUMP]:0C025231
1038:d=4  hl=2 l=  17 cons:     SEQUENCE
1040:d=5  hl=2 l=  10 prim:      OBJECT            :2.9.1.6.2.6.1.9.9.4.3
1052:d=5  hl=2 l=   3 prim:      OCTET STRING      [HEX DUMP]:0C0133
...
...

这是我的解决方案,

供参考。

func getCustomExtensions(serverCertFile string, customOIDPrefix string) ([]pkix.Extension, bool) {
certBytes, err := os.ReadFile(serverCertFile)
if err != nil {
return nil, false
}
block, _ := pem.Decode(certBytes)
if block.Type == "CERTIFICATE" {
certificate, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, false
}
var extensions []pkix.Extension
for _, ext := range certificate.Extensions {
// filter the custom extensions by customOID
if strings.Contains(ext.Id.String(), customOIDPrefix) {
extensions = append(extensions, ext)
}
}
return extensions, true
}
return nil, false
}

相关内容

  • 没有找到相关文章

最新更新