Home > Mobile >  How to get CN from a certificate in Golang
How to get CN from a certificate in Golang

Time:10-01

Is there any way to extract CN from X509Certificate in Golang.

Previously we did something like this in Java.

private String getCNFromCertificate() throws InvalidNameException, CertificateException, IOException {
      X509Certificate certificate = getCert(DeploymentConfiguration.getPemCertPath().get());
      String commonName = new LdapName(certificate.getSubjectX500Principal().getName()).getRdns().stream()
              .filter(i -> i.getType().equalsIgnoreCase("CN")).findFirst().get().getValue().toString();
        return commonName;
}

Are there any packages in Golang which can do similar task. Or what could be better alternative to extract CN from Certificate in Golang.

Thank you in advance.

CodePudding user response:

The question is ill-formed, I tink: there's no such thing as "CN" in an X.509 certificate. CN is an abbreviation for "Common Name", which is one form of referring to entities in the X.509 PKI. What you're probably after is the "Subject" field of a certificate—that is, the entity who that certificate was issued for.

If so, you need the Subject field of x509.Certificate, which is a special compound data type containing CommonName, among other things.

See this for a quick overview of what place the CN takes in naming an entity.

The crypto/x509 is a stock package (that is, provided by the Go's standard library).

CodePudding user response:

The gist of how to load & parse a public cert:

bs, err := os.ReadFile("/tmp/google.crt")  // handle error

block, _ := pem.Decode(bs)
if block == nil {
    log.Fatal("failed to parse PEM block containing the public key")
}

cert, err := x509.ParseCertificate(block.Bytes) // handle error

log.Printf("Subject:   %q", cert.Subject)

// Subject:   "CN=*.google.com"

Warning: since go 1.15 the use of CN to store hostnames is now deprecated:

The deprecated, legacy behavior of treating the CommonName field on X.509 certificates as a host name when no Subject Alternative Names are present is now disabled by default. It can be temporarily re-enabled by adding the value x509ignoreCN=0 to the GODEBUG environment variable.

If you want to find a hostname (or hostname wildcard) within a certification, one should use the SAN (Subject Alternative Names) section - where there is a DNS section. This is captured in the DNSNames field of the x509.Certificate struct:

log.Printf("DNS names: % v", cert.DNSNames)

// DNS names: [*.google.com *.appengine.google.com *.bdn.dev *.origin-test.bdn.dev *.cloud.google.com ...

Playground Example

  • Related