在 go 中创建具有特定主题顺序的 CSR

问题描述 投票:0回答:1

我正在尝试使用加密库在 go 中创建证书签名请求。由 生成的 CSR 的主题为“主题:C = IN、L = loc、O = Example Org、OU = OU1 + OU = OU2、CN = example.com”。我想将主题的顺序更改为“主题:C = IN,O = 示例组织,OU = OU1 + OU = OU2,L = loc,CN = example.com”。

我使用以下代码生成了 CSR。

package main

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

func main() {
    privKey, err := rsa.GenerateKey(rand.Reader, 2048)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    csrTemplate := x509.CertificateRequest{
        Subject: pkix.Name{
            Country:            []string{"IN"},
            Organization:       []string{"Example Org"},
            OrganizationalUnit: []string{"OU1", "OU2"},
            Locality:           []string{"loc"},
            CommonName:         "example.com",
        },
        EmailAddresses: []string{"[email protected]"},
    }

    csrBytes, err := x509.CreateCertificateRequest(rand.Reader, &csrTemplate, privKey)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    csrPem := pem.EncodeToMemory(&pem.Block{
        Type:  "CERTIFICATE REQUEST",
        Bytes: csrBytes,
    })

    fmt.Println(string(csrPem))
}

此代码生成主题为“主题:C = IN,L = loc,O = 示例组织,OU = OU1 + OU = OU2,CN = example.com”的 CSR。我可以使用下面的 openssl 命令生成具有所需主题顺序的 CSR

openssl req -new -sha256 -key my-private-key.pem -out my-csr1.pem -subj '/C=IN/O=Org/OU=OU1/OU=OU2/L=loc/CN=example.com'

如何在 Go 中做同样的事情?

go x509 csr
1个回答
1
投票

我不清楚为什么你想以这个特定的顺序将 RDN 放在主题中。我认为,任何依赖于特定顺序的软件都有些损坏。当然,损坏的软件是存在的,有时唯一的方法就是解决它。

也有一种方法可以使用 golang 来做到这一点。但您不能简单地使用 pkix.Name 中的匹配字段名称,因为这些名称将以固定顺序序列化。要获得您自己的订单,您需要使用

ExtraNames
,然后按您需要的顺序提供 RDN:

    var (
        oidCountry            = []int{2, 5, 4, 6}
        oidOrganization       = []int{2, 5, 4, 10}
        oidOrganizationalUnit = []int{2, 5, 4, 11}
        oidCommonName         = []int{2, 5, 4, 3}
        oidLocality           = []int{2, 5, 4, 7}
    )
    csrTemplate := x509.CertificateRequest{
        Subject: pkix.Name{
            ExtraNames: []pkix.AttributeTypeAndValue{
                { oidCountry, "IN" },
                { oidOrganization, "Example Org" },
                { oidOrganizationalUnit, "OU1" },
                { oidOrganizationalUnit, "OU2" },
                { oidLocality, "loc" },
                { oidCommonName, "example.com" },
            },
        },
        EmailAddresses: []string{"[email protected]"},
    }
© www.soinside.com 2019 - 2024. All rights reserved.