英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论