I have an x509 certificate's subject distinguished name (DN) from an X.509 certificate. I want to extract common name (CN) from it. Is there a way to do it via crypto/x509
or any other library in Go?
For Example, if the subject's distinguished name is:
CN=AMA AMI SA APB MDE MADB MDS LE.AXVD-04954-19-17.,OU=Abc,O=DA.CB.AcbDinema.com,dnQualifier=PY0aT8abfcQeUyquTe4w5RVasfY=
then I want to extract common name (CN) part (AMA AMI SA APB MDE MADB MDS LE.AXVD-04954-19-17.
) out of it.
There is nothing in the Go standard library to parse it for you (it only handles ASN.1 encoded distinguished names), but you treat it as just a string and parse it yourself.
Here is an example using regexps. A word of warning: there is no guarantee that this will work in all cases. For example, I've seen cases of lowercase CN
, or ordering may change, or just bad formatting.
package main
import (
"fmt"
"regexp"
"strings"
)
func main() {
subjectString := "CN=AMA AMI SA APB MDE MADB MDS LE.AXVD-04954-19-17.,OU=Abc,O=DA.CB.AcbDinema.com,dnQualifier=PY0aT8abfcQeUyquTe4w5RVasfY="
re := regexp.MustCompile("CN=([^,]+)")
matches := re.FindStringSubmatch(subjectString)
fmt.Println(matches[1])
commonNameParts := strings.Split(matches[1], " ")
fmt.Println(commonNameParts)
}
Outputs the full CN string and a slice of the individual components of the CommonName:
AMA AMI SA APB MDE MADB MDS LE.AXVD-04954-19-17.
[AMA AMI SA APB MDE MADB MDS LE.AXVD-04954-19-17.]