forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cert.go
98 lines (82 loc) · 2.41 KB
/
cert.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
87
88
89
90
91
92
93
94
95
96
97
98
package cert
import (
"bytes"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"fmt"
"strings"
"time"
"github.com/pkg/errors"
)
type CertificateInfo struct {
Algorithm string `json:"algorithm"`
CN string `json:"cn"`
Fingerprint string `json:"certFingerprint"`
ExpiresAt time.Time `json:"expiresAt"`
IssuedAt time.Time `json:"issuedAt"`
Issuer string `json:"issuer"`
KeySize int `json:"keySize"`
SerialNumber string `json:"serialNumber"`
SubjectAlternativeNames []string `json:"subjectAlternativeNames"`
Version int `json:"version"`
}
func Info(pemCerts, pemKey string) (*CertificateInfo, error) {
block, _ := pem.Decode([]byte(pemKey))
if block == nil {
return nil, errors.New("failed to parse key, not valid pem format")
}
key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, errors.Wrap(err, "failed to read private key")
}
rest := []byte(pemCerts)
for {
block, rest = pem.Decode(rest)
var certInfo CertificateInfo
if block == nil {
break
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, errors.Wrap(err, "failed to parse certificate")
}
pubKey, ok := cert.PublicKey.(*rsa.PublicKey)
if !ok {
continue
}
if pubKey.N.Cmp(key.N) != 0 {
continue
}
certInfo.Algorithm = "RSA"
certInfo.Fingerprint = fingerprint(block.Bytes)
certInfo.CN = cert.Subject.CommonName
certInfo.ExpiresAt = cert.NotAfter
certInfo.IssuedAt = cert.NotBefore
certInfo.Issuer = cert.Issuer.CommonName
certInfo.KeySize = len(key.N.Bytes())
certInfo.SerialNumber = cert.SerialNumber.String()
certInfo.Version = cert.Version
for _, name := range cert.DNSNames {
certInfo.SubjectAlternativeNames = append(certInfo.SubjectAlternativeNames, name)
}
for _, ip := range cert.IPAddresses {
certInfo.SubjectAlternativeNames = append(certInfo.SubjectAlternativeNames, ip.String())
}
return &certInfo, nil
}
return nil, fmt.Errorf("failed to find cert that matched private key")
}
func fingerprint(data []byte) string {
digest := sha1.Sum(data)
buf := &bytes.Buffer{}
for i := 0; i < len(digest); i++ {
if buf.Len() > 0 {
buf.WriteString(":")
}
buf.WriteString(strings.ToUpper(hex.EncodeToString(digest[i : i+1])))
}
return buf.String()
}