golang subject dn from x509 cert

前端 未结 7 2172
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-18 08:10

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()\"

相关标签:
7条回答
  • 2020-12-18 08:58

    In order to get complete subject DN (or issuer DN) from an x509 certificate, you may use next code:

    cert, err := x509.ParseCertificate(certData)
    if err != nil {
        return err
    }
    
    var subject pkix.RDNSequence
    if _, err := asn1.Unmarshal(cert.RawSubject, &subject); err != nil {
        return err
    }
    
    fmt.Plrintln(subject.String()
    

    Similarly, if you need to get only some specific object value from the subject (or issuer) you may use next approach. Example below retrieves UID from subject (which is not defined in the stdlib https://github.com/golang/go/issues/25667)

    // http://www.alvestrand.no/objectid/0.9.2342.19200300.100.1.1.html
    const oidUserID = "0.9.2342.19200300.100.1.1"
    var UID string
    
    cert, err := x509.ParseCertificate(certData)
    if err != nil {
        return err
    }
    
    // manually parsing the Certificate subject to get the
    // UID field, which is being ignored by the stdlib
    // https://github.com/golang/go/issues/25667
    var subject pkix.RDNSequence
    if _, err := asn1.Unmarshal(cert.RawSubject, &subject); err != nil {
        return err
    }
    
    for _, s := range subject {
        for _, i := range s {
            if i.Type.String() == oidUserID {
                if v, ok := i.Value.(string); ok {
                    UID = v
                }
            }
        }
    }
    
    fmt.Println(UID)
    

    UPDATE: Simplified way to get the UID, thanks to @FiloSottile:

    // http://www.alvestrand.no/objectid/0.9.2342.19200300.100.1.1.html
    var oidUserID = []int{0, 9, 2342, 19200300, 100, 1, 1}
    var UID string
    
    cert, err := x509.ParseCertificate(certData)
    if err != nil {
        return err
    }
    
    // reading the UID from list of unprased 
    // objects from Subject
    for _, n := range cert.Subject.Names {
        if n.Type.Equal(oidUserID) {
            if v, ok := n.Value.(string); ok {
                UID = v
            }
        }
    }
    
    fmt.Println(UID)
    
    0 讨论(0)
提交回复
热议问题