How to Extract the Subject DN from an X.509 Certificate in Go?

Mary-Kate Olsen
Release: 2024-11-02 15:07:30
Original
397 people have browsed it

How to Extract the Subject DN from an X.509 Certificate in Go?

Extracting the Subject DN from an X.509 Certificate in Go

Problem

Generating a string representation of the subject DN (or issuer DN) from an X.509 certificate in Go can be challenging. The default methods available for the pkix.Name type lack a straightforward way to retrieve this information.

Solution

Using the following custom function, it is possible to convert the certificate's subject or issuer DN into a string:

<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 {
                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 retrieve the subject DN from a certificate, call the getDNFromCert 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 X.509 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!