How to Extract the Subject DN from an X509 Certificate in Go?

Barbara Streisand
Release: 2024-10-31 04:44:02
Original
385 people have browsed it

How to Extract the Subject DN from an X509 Certificate in Go?

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>
Copy after login

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>
Copy after login

Example Output:

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

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!