-
Notifications
You must be signed in to change notification settings - Fork 1
/
certificate_parse.go
86 lines (72 loc) · 1.57 KB
/
certificate_parse.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"crypto/x509"
"encoding/pem"
"github.com/alexeyco/simpletable"
"io"
"os"
)
type ParseCmd struct {
CertFile string `arg:"positional" description:"A certificate in .pem format"`
}
func doParseCertificate(cmd *ParseCmd) {
if cmd == nil {
logger.Fatalf("cmd cannot be nil")
}
if cmd.CertFile == "" {
logger.Errorf("please specify a certificate file")
return
}
f, err := os.Open(cmd.CertFile)
if err != nil {
logger.Errorf("unable to open certificate file: %v", err)
return
}
var fileBytes []byte
fileBytes, err = io.ReadAll(f)
if err != nil {
logger.Errorf("unable to read file: %v", err)
return
}
err = f.Close()
if err != nil {
logger.Errorf("unable to close file: %v", err)
return
}
showCert(fileBytes)
}
func showCert(fileBytes []byte) {
input := fileBytes
var certs []*x509.Certificate
for {
pemBlock, rest := pem.Decode(input)
if pemBlock == nil {
break
}
if rest == nil {
break
}
input = rest
if pemBlock.Type != "CERTIFICATE" {
logger.Errorf("invalid pem block type: %s", pemBlock.Type)
return
}
cert, err := x509.ParseCertificate(pemBlock.Bytes)
if err != nil {
logger.Errorf("unable to parse certificate: %v", err)
return
}
certs = append(certs, cert)
}
printCertChain(certs)
}
func printCertificate(cert *x509.Certificate) []*simpletable.Cell {
if cert == nil {
logger.Errorf("cert cannot be nil!")
return nil
}
return []*simpletable.Cell{
{Align: simpletable.AlignLeft, Text: cert.Subject.CommonName},
{Align: simpletable.AlignLeft, Text: cert.Issuer.CommonName},
}
}