如何使用Go在证书中添加SAN扩展

时间:2018-02-16 08:15:11

标签: go openssl x509certificate subject-alternative-name

我需要在证书中指定registeredID。

所以我在使用OpenSSL签名证书的配置文件中添加它。

[ alternate_names ]
DNS.1 = localhost
RID.1 = 1.2.3.4.5.5

此处,1.2.3.4.5.5是OID。

我在Stack Overflow中关注了How to format an OID Subject Alt Name entry in a openssl.cnf file

现在,我想在Go中生成证书。下面是我当前的配置

cfg := cert.Config{
    CommonName:   name,
    Organization: []string{"Elasticsearch Operator"},
    AltNames: cert.AltNames{
        DNSNames: []string{
            "localhost",
        },
    },
    Usages: []x509.ExtKeyUsage{
        x509.ExtKeyUsageServerAuth,
        x509.ExtKeyUsageClientAuth,
    },
}

在此配置中,如何添加OID号。

1 个答案:

答案 0 :(得分:4)

使用Go。没有直接的方法在证书中添加OBJECT IDENTIFIER。

我们找到了一个自定义解决方案。

Go提供了在证书

中添加其他SAN信息的选项
x509.Certificate{
    ExtraExtensions: []pkix.Extension{
        {
            // Here, We add SAN additional with specific ID
        },
    },
}

根据2.5.29.17 - Subject Alternative Name,SAN的OID为2.5.29.17

让我们说,我们将在SAN中添加registeredID 1.2.3.4.5.5。此RID需要添加为标记#8。 (根据2.5.29.17

因此,此扩展的字节值为[]byte{0x88, 0x05, 0x2A, 0x03, 0x04, 0x05, 0x05}

下面,

  • 0x88是特定于上下文的#8
  • 的标记值
  • 0x05是编码值的长度
  • 0x2A, 0x03, 0x04, 0x05, 0x05的编码值为1.2.3.4.5.5
    • 0x2A来自4240 * 1 + 2,此处为12是ID的前两个值。

所以,最后

rawValue := []asn1.RawValue{
    {FullBytes: []byte{0x88, 0x05, 0x2A, 0x03, 0x04, 0x05, 0x05}},
}
rawByte, _ := asn1.Marshal(rawValue)

_ = x509.Certificate{
    ExtraExtensions: []pkix.Extension{
        {
            Id:    asn1.ObjectIdentifier{2, 5, 29, 17},
            Value: rawByte,
        },
    },
}