forked from hyperledger-archives/fabric
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cert.go
executable file
·244 lines (201 loc) · 6.44 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package utils
import (
"crypto/ecdsa"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/pem"
"errors"
"math/big"
"net"
"time"
)
var (
// TCertEncTCertIndex oid for TCertIndex
TCertEncTCertIndex = asn1.ObjectIdentifier{1, 2, 3, 4, 5, 6, 7}
)
// DERToX509Certificate converts der to x509
func DERToX509Certificate(asn1Data []byte) (*x509.Certificate, error) {
return x509.ParseCertificate(asn1Data)
}
// PEMtoCertificate converts pem to x509
func PEMtoCertificate(raw []byte) (*x509.Certificate, error) {
block, _ := pem.Decode(raw)
if block == nil {
return nil, errors.New("No PEM block available")
}
if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
return nil, errors.New("Not a valid CERTIFICATE PEM block")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
return cert, nil
}
// PEMtoDER converts pem to der
func PEMtoDER(raw []byte) ([]byte, error) {
block, _ := pem.Decode(raw)
if block == nil {
return nil, errors.New("No PEM block available")
}
if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
return nil, errors.New("Not a valid CERTIFICATE PEM block")
}
return block.Bytes, nil
}
// PEMtoCertificateAndDER converts pem to x509 and der
func PEMtoCertificateAndDER(raw []byte) (*x509.Certificate, []byte, error) {
block, _ := pem.Decode(raw)
if block == nil {
return nil, nil, errors.New("No PEM block available")
}
if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
return nil, nil, errors.New("Not a valid CERTIFICATE PEM block")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, nil, err
}
return cert, block.Bytes, nil
}
// DERCertToPEM converts der to pem
func DERCertToPEM(der []byte) []byte {
return pem.EncodeToMemory(
&pem.Block{
Type: "CERTIFICATE",
Bytes: der,
},
)
}
// GetCriticalExtension returns a requested critical extension. It also remove it from the list
// of unhandled critical extensions
func GetCriticalExtension(cert *x509.Certificate, oid asn1.ObjectIdentifier) ([]byte, error) {
for i, ext := range cert.UnhandledCriticalExtensions {
if IntArrayEquals(ext, oid) {
cert.UnhandledCriticalExtensions = append(cert.UnhandledCriticalExtensions[:i], cert.UnhandledCriticalExtensions[i+1:]...)
break
}
}
for _, ext := range cert.Extensions {
if IntArrayEquals(ext.Id, oid) {
return ext.Value, nil
}
}
return nil, errors.New("Failed retrieving extension.")
}
// NewSelfSignedCert create a self signed certificate
func NewSelfSignedCert() ([]byte, interface{}, error) {
privKey, err := NewECDSAKey()
if err != nil {
return nil, nil, err
}
testExtKeyUsage := []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}
testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}}
extraExtensionData := []byte("extra extension")
commonName := "test.example.com"
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
CommonName: commonName,
Organization: []string{"Σ Acme Co"},
Country: []string{"US"},
ExtraNames: []pkix.AttributeTypeAndValue{
{
Type: []int{2, 5, 4, 42},
Value: "Gopher",
},
// This should override the Country, above.
{
Type: []int{2, 5, 4, 6},
Value: "NL",
},
},
},
NotBefore: time.Unix(1000, 0),
NotAfter: time.Unix(100000, 0),
SignatureAlgorithm: x509.ECDSAWithSHA384,
SubjectKeyId: []byte{1, 2, 3, 4},
KeyUsage: x509.KeyUsageCertSign,
ExtKeyUsage: testExtKeyUsage,
UnknownExtKeyUsage: testUnknownExtKeyUsage,
BasicConstraintsValid: true,
IsCA: true,
OCSPServer: []string{"http://ocsp.example.com"},
IssuingCertificateURL: []string{"http://crt.example.com/ca1.crt"},
DNSNames: []string{"test.example.com"},
EmailAddresses: []string{"gopher@golang.org"},
IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
PolicyIdentifiers: []asn1.ObjectIdentifier{[]int{1, 2, 3}},
PermittedDNSDomains: []string{".example.com", "example.com"},
CRLDistributionPoints: []string{"http://crl1.example.com/ca1.crl", "http://crl2.example.com/ca1.crl"},
ExtraExtensions: []pkix.Extension{
{
Id: []int{1, 2, 3, 4},
Value: extraExtensionData,
},
},
}
cert, err := x509.CreateCertificate(rand.Reader, &template, &template, &privKey.PublicKey, privKey)
if err != nil {
return nil, nil, err
}
return cert, privKey, nil
}
func CheckCertPKAgainstSK(x509Cert *x509.Certificate, privateKey interface{}) error {
switch pub := x509Cert.PublicKey.(type) {
case *rsa.PublicKey:
priv, ok := privateKey.(*rsa.PrivateKey)
if !ok {
return errors.New("Private key type does not match public key type")
}
if pub.N.Cmp(priv.N) != 0 {
return errors.New("Private key does not match public key")
}
case *ecdsa.PublicKey:
priv, ok := privateKey.(*ecdsa.PrivateKey)
if !ok {
return errors.New("Private key type does not match public key type")
}
if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {
return errors.New("Private key does not match public key")
}
default:
return errors.New("Unknown public key algorithm")
}
return nil
}
func CheckCertAgainRoot(x509Cert *x509.Certificate, certPool *x509.CertPool) ([][]*x509.Certificate, error) {
opts := x509.VerifyOptions{
// TODO DNSName: "test.example.com",
Roots: certPool,
}
return x509Cert.Verify(opts)
}
func CheckCertAgainstSKAndRoot(x509Cert *x509.Certificate, privateKey interface{}, certPool *x509.CertPool) error {
if err := CheckCertPKAgainstSK(x509Cert, privateKey); err != nil {
return err
}
if _, err := CheckCertAgainRoot(x509Cert, certPool); err != nil {
return err
}
return nil
}