Go:如何将扩展名(subjectAltName)添加到x509.Certificate?

时间:2014-10-18 15:43:45

标签: go x509

我正在创建一个CA证书。我想添加subjectAltName扩展名,其中包含一些值,如email或crl或公共证书位置等。

package main

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "crypto/x509/pkix"
    "encoding/asn1"
    "encoding/pem"
    "fmt"
    "math/big"
    "os"
    "time"
    //"net"
    //"strconv"
)

func main() {
    template := x509.Certificate{}
    template.Subject = pkix.Name{
        Organization:  []string{"domain.tld", "My Name"},
        StreetAddress: []string{"Whatever. 123"},
        PostalCode:    []string{"12345"},
        Province:      []string{"Redneckville"},
        Locality:      []string{"Woods"},
        Country:       []string{"US"},
        CommonName:    "CA domain my name",
    }

    template.NotBefore = time.Now()
    template.NotAfter = template.NotBefore.Add(87658 * time.Hour)
    template.KeyUsage = x509.KeyUsageCertSign | x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCRLSign
    template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}
    template.IsCA = true
    template.BasicConstraintsValid = true
    extSubjectAltName := pkix.Extension{}
    extSubjectAltName.Id = asn1.ObjectIdentifier{2, 5, 29, 17}
    extSubjectAltName.Critical = false
    var e error
    extSubjectAltName.Value, e = asn1.Marshal([]string{`email:mail@domain.tld`, `URI:http://ca.domain.tld/`})
    if e != nil {
        fmt.Println(e.Error())
        return
    }
    template.Extensions = []pkix.Extension{extSubjectAltName}

    priv, err := rsa.GenerateKey(rand.Reader, 4096)
    if err != nil {
        fmt.Println("Failed to generate private key:", err)
        os.Exit(1)
    }
    serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
    template.SerialNumber, err = rand.Int(rand.Reader, serialNumberLimit)
    if err != nil {
        fmt.Println("Failed to generate serial number:", err)
        os.Exit(1)
    }
    derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
    if err != nil {
        fmt.Println("Failed to create certificate:", err)
        os.Exit(1)
    }
    certOut, err := os.Create("ca.crt")
    if err != nil {
        fmt.Println("Failed to open ca.pem for writing:", err)
        os.Exit(1)
    }
    pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
    certOut.Close()
    keyOut, err := os.OpenFile("ca.key", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
    if err != nil {
        fmt.Println("failed to open ca.key for writing:", err)
        os.Exit(1)
    }
    pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
    keyOut.Close()
}

当我这样做时,结果是

X509v3 extensions:
    X509v3 Key Usage: critical
        Digital Signature, Key Encipherment, Certificate Sign, CRL Sign
    X509v3 Extended Key Usage: 
        TLS Web Client Authentication, TLS Web Server Authentication
    X509v3 Basic Constraints: critical
        CA:TRUE

所以,但我期待像

这样的东西
    X509v3 Subject Alternative Name: 
        email:caoperator@disig.sk, URI:http://www.disig.sk/ca

如何使用这些值添加扩展名?

我也尝试过价值:[]byte(``email:my@email.com, URI:http://some.tld/uri``)<双“”“因为格式化

3 个答案:

答案 0 :(得分:4)

extSubjectAltName := pkix.Extension{}
extSubjectAltName.Id = asn1.ObjectIdentifier{2, 5, 29, 17}
extSubjectAltName.Critical = false
extSubjectAltName.Value = []byte(`email:my@mail.tld, URI:http://ca.dom.tld/`)
template.ExtraExtensions = []pkix.Extension{extSubjectAltName}

请注意: template.ExtraExtensions代替template.Extensions

答案 1 :(得分:0)

我知道这是一个迟到的答案,但是这个问题出现在谷歌搜索golang x509 SubjectAltName,所以我想我将为未来的Google员工投入2美分:

根据the x509.Certificate spec,SubjectAltNames应放在x509.Certificate的DNSNameEmailAddressesIPAddresses属性中。

你的例子+快乐的SAN:

package main

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "crypto/x509/pkix"
    "encoding/pem"
    "fmt"
    "math/big"
    "os"
    "time"
)

func main() {
    template := x509.Certificate{}
    template.Subject = pkix.Name{
        Organization:  []string{"domain.tld", "My Name"},
        StreetAddress: []string{"Whatever. 123"},
        PostalCode:    []string{"12345"},
        Province:      []string{"Redneckville"},
        Locality:      []string{"Woods"},
        Country:       []string{"US"},
        CommonName:    "CA domain my name",
    }

    template.NotBefore = time.Now()
    template.NotAfter = template.NotBefore.Add(87658 * time.Hour)
    template.KeyUsage = x509.KeyUsageCertSign | x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCRLSign
    template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}
    template.IsCA = true
    template.BasicConstraintsValid = true
    template.DNSNames = []string{"ca.my.domain", "ca"}

    priv, err := rsa.GenerateKey(rand.Reader, 4096)
    if err != nil {
        fmt.Println("Failed to generate private key:", err)
        os.Exit(1)
    }
    serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
    template.SerialNumber, err = rand.Int(rand.Reader, serialNumberLimit)
    if err != nil {
        fmt.Println("Failed to generate serial number:", err)
        os.Exit(1)
    }
    derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
    if err != nil {
        fmt.Println("Failed to create certificate:", err)
        os.Exit(1)
    }
    certOut, err := os.Create("ca.crt")
    if err != nil {
        fmt.Println("Failed to open ca.pem for writing:", err)
        os.Exit(1)
    }
    pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
    certOut.Close()
    keyOut, err := os.OpenFile("ca.key", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
    if err != nil {
        fmt.Println("failed to open ca.key for writing:", err)
        os.Exit(1)
    }
    pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
    keyOut.Close()
}

答案 2 :(得分:0)

X.509扩展名为ASN.1 DER编码。放置ASCII表示 SAN扩展直接进入证书的二进制文件将无法正常工作,并将截断数据。这可能是OP问题背后的原因。

如果您尝试添加Go支持的任何SAN,那么Cole Brumley指定的方式就是这样做的。这是因为Go处理ASN.1序列化,这避免了您需要编写任何额外的代码。查看主题备用名称值部分,了解Go支持的SAN:https://godoc.org/crypto/x509#Certificate

如果您尝试添加Go不支持的某些SAN类型(如URI),请查看如何使用原始值对dns,ip和email进行编组操作,这可能会帮助您解决问题: https://github.com/golang/go/blob/2a26f5809e4e80e7d8d4e20b9965efb2eefe71c5/src/crypto/x509/x509.go#L1439-L1456。您可能需要找出相应的标签是什么。