dq1230123 2016-08-24 14:17
浏览 190

来自x509证书的golang主题dn

Is there any easy way to get the complete subject DN (or issuer DN) from an x509 certificate in go as a string?

I was not able to find any methods like ".String()" in pkix.Name

  • 写回答

5条回答 默认 最新

  • duankuang7928 2016-08-25 06:26
    关注

    Solution (thanks to a colleague):

    var oid = map[string]string{
        "2.5.4.3":                    "CN",
        "2.5.4.4":                    "SN",
        "2.5.4.5":                    "serialNumber",
        "2.5.4.6":                    "C",
        "2.5.4.7":                    "L",
        "2.5.4.8":                    "ST",
        "2.5.4.9":                    "streetAddress",
        "2.5.4.10":                   "O",
        "2.5.4.11":                   "OU",
        "2.5.4.12":                   "title",
        "2.5.4.17":                   "postalCode",
        "2.5.4.42":                   "GN",
        "2.5.4.43":                   "initials",
        "2.5.4.44":                   "generationQualifier",
        "2.5.4.46":                   "dnQualifier",
        "2.5.4.65":                   "pseudonym",
        "0.9.2342.19200300.100.1.25": "DC",
        "1.2.840.113549.1.9.1":       "emailAddress",
        "0.9.2342.19200300.100.1.1":  "userid",
    }
    
    func getDNFromCert(namespace pkix.Name, sep string) (string, error) {
        subject := []string{}
        for _, s := range namespace.ToRDNSequence() {
            for _, i := range s {
                if v, ok := i.Value.(string); ok {
                    if name, ok := oid[i.Type.String()]; ok {
                        // <oid name>=<value>
                        subject = append(subject, fmt.Sprintf("%s=%s", name, v))
                    } else {
                        // <oid>=<value> if no <oid name> is found
                        subject = append(subject, fmt.Sprintf("%s=%s", i.Type.String(), v))
                    }
                } else {
                    // <oid>=<value in default format> if value is not string
                    subject = append(subject, fmt.Sprintf("%s=%v", i.Type.String, v))
                }
            }
        }
        return sep + strings.Join(subject, sep), nil
    }
    

    calling the function:

    subj, err := getDNFromCert(x509Cert.Subject, "/")
    if err != nil {
       // do error handling
    }
    fmt.Println(subj)
    

    output (example):

    /C=US/O=some organization/OU=unit/CN=common name
    

    this seems to be the only "easy" solution

    评论

报告相同问题?

悬赏问题

  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了