Search code examples
gox509pem

Parsing and printing X.509 attributes from PEM


I'm looking for a simple example for parsing an X.509 PEM in go and dumping the values to stdout. Can anybody provide an example ?


Solution

  • You want to use encoding.pem to decode the pem file, which will give you the DER blocks you can decode with the crypto/x509 package.

    For example:

    certPEMBlock, err := ioutil.ReadFile(certFile)
    if err != nil {
        log.Fatal(err)
    }
    
    var blocks [][]byte
    for {
        var certDERBlock *pem.Block
        certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
        if certDERBlock == nil {
            break
        }
    
        if certDERBlock.Type == "CERTIFICATE" {
            blocks = append(blocks, certDERBlock.Bytes)
        }
    }
    
    for _, block := range blocks {
        cert, err := x509.ParseCertificate(block)
        if err != nil {
            log.Println(err)
            continue
        }
    
        fmt.Println("Certificate:")
        fmt.Printf("\tSubject: %+v\n", cert.Subject)
        fmt.Printf("\tDNS Names: %+v\n", cert.DNSNames)
        fmt.Printf("\tEmailAddresses: %+v\n", cert.EmailAddresses)
        fmt.Printf("\tIPAddresses: %+v\n", cert.IPAddresses)
    }