-
Notifications
You must be signed in to change notification settings - Fork 402
/
certificates.go
113 lines (98 loc) · 2.24 KB
/
certificates.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package debugging
import (
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509"
"encoding/json"
"fmt"
"math/big"
"github.com/nsf/jsondiff"
)
var (
diffOpts = jsondiff.DefaultConsoleOptions()
)
// DebugCert is a subset of the most relevant fields from an x509.Certificate for debugging.
type DebugCert struct {
Cert *x509.Certificate
}
// NewDebugCert converts an *x509.Certificate into a DebugCert.
func NewDebugCert(cert x509.Certificate) DebugCert {
return DebugCert{
Cert: &cert,
}
}
// PrintJSON uses a json marshaler to pretty-print arbitrary data for debugging
// with special considerations for certain, specific types.
func PrintJSON(data interface{}, label string) {
var (
jsonBytes []byte
err error
)
switch d := data.(type) {
case x509.Certificate:
data = NewDebugCert(d)
case *x509.Certificate:
data = NewDebugCert(*d)
case *ecdsa.PublicKey:
data = struct {
X *big.Int
Y *big.Int
}{
d.X, d.Y,
}
case *ecdsa.PrivateKey:
data = struct {
X *big.Int
Y *big.Int
D *big.Int
}{
d.X, d.Y, d.D,
}
case *rsa.PublicKey:
data = struct {
N *big.Int
E int
}{
d.N, d.E,
}
case *rsa.PrivateKey:
data = struct {
N *big.Int
E int
D *big.Int
Primes []*big.Int
}{
d.N, d.E, d.D, d.Primes,
}
}
jsonBytes, err = json.MarshalIndent(data, "", "\t\t")
if label != "" {
fmt.Println(label + ": ---================================================================---")
}
if err != nil {
fmt.Printf("ERROR: %s", err.Error())
}
fmt.Println(string(jsonBytes))
fmt.Println("")
}
// Cmp is used to compare 2 DebugCerts against each other and print the diff.
func (c DebugCert) Cmp(c2 DebugCert, label string) error {
fmt.Println("diff " + label + " ---================================================================---")
cJSON, err := c.JSON()
if err != nil {
return err
}
c2JSON, err := c2.JSON()
if err != nil {
return err
}
diffType, diff := jsondiff.Compare(cJSON, c2JSON, &diffOpts)
fmt.Printf("Difference type: %s\n======\n%s\n", diffType, diff)
return nil
}
// JSON serializes the certificate to JSON.
func (c DebugCert) JSON() ([]byte, error) {
return json.Marshal(c.Cert)
}