解析和打印 PEM 格式的 X.509 属性。

huangapple go评论82阅读模式
英文:

Parsing and printing X.509 attributes from PEM

问题

我正在寻找一个简单的示例,用于在Go中解析X.509 PEM并将值转储到stdout。有人可以提供一个示例吗?

英文:

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 ?

答案1

得分: 2

你想使用encoding.pem来解码pem文件,这将给你DER块,你可以使用crypto/x509包来解码。

例如:

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)
}
英文:

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)
}

huangapple
  • 本文由 发表于 2016年4月15日 21:45:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/36648934.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定