How to Extract Subject DN from X509 Certificate in Go
Retrieving the complete subject distinguished name (DN) from an X509 certificate in Go as a string can be challenging. Despite lacking a dedicated ".String()" method for the pkix.Name type, there is a multifaceted solution.
Solution:
The following function leverages a predefined map to translate OIDs into meaningful field names (e.g., "CN" for Common Name):
<code class="go">import ( "fmt" "strings" "crypto/x509" "crypto/x509/pkix" ) var oid = map[string]string{ "2.5.4.3": "CN", "2.5.4.6": "C", "2.5.4.7": "L", "2.5.4.8": "ST", "2.5.4.10": "O", "2.5.4.11": "OU", "1.2.840.113549.1.9.1": "emailAddress", } 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 { subject = append(subject, fmt.Sprintf("%s=%s", name, v)) } else { subject = append(subject, fmt.Sprintf("%s=%s", i.Type.String(), v)) } } else { subject = append(subject, fmt.Sprintf("%s=%v", i.Type.String(), v)) } } } return sep + strings.Join(subject, sep), nil }</code>
Usage:
To extract the subject DN, invoke the function as follows:
<code class="go">subj, err := getDNFromCert(x509Cert.Subject, "/") if err != nil { // Error handling } fmt.Println(subj)</code>
Example Output:
/C=US/O=some organization/OU=unit/CN=common name
The above is the detailed content of How to Extract the Subject DN from an X509 Certificate in Go?. For more information, please follow other related articles on the PHP Chinese website!