Retrieve Complete Subject or Issuer DN from X509 Certificate in Go
Retrieving the complete subject or issuer Distinguished Name (DN) from an X509 certificate as a string can be accomplished using a few steps.
Solution Details:
Map OIDs to Attribute Names:
Convert RDNSequence to String:
Build Subject DN String:
Call the Function:
Example Usage:
<code class="go">func main() { // Obtain the X509 certificate x509Cert, err := LoadCert(pemBytes) if err != nil { // Handle error } // Retrieve subject DN subj, err := getDNFromCert(x509Cert.Subject, "/") if err != nil { // Handle error } fmt.Println("Subject DN:", subj) }</code>
Function Definition:
<code class="go">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 { subject = append(subject, fmt.Sprintf("%v=%v", i.Type.String(), v)) } else { subject = append(subject, fmt.Sprintf("%v=%v", i.Type.String(), i.Value)) } } } return sep + strings.Join(subject, sep), nil }</code>
Expected Output:
Subject DN: /C=US/O=some organization/OU=unit/CN=common name
The above is the detailed content of How to Extract the Complete Subject or Issuer DN from an X509 Certificate in Go?. For more information, please follow other related articles on the PHP Chinese website!