/
ca.go
430 lines (380 loc) · 9.42 KB
/
ca.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package ca
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"github.com/VoneChain-CS/fabric-gm/bccsp"
"github.com/VoneChain-CS/fabric-gm/bccsp/gm"
"github.com/tjfoc/gmsm/sm2"
"io/ioutil"
"math/big"
"net"
"os"
"path/filepath"
"strings"
"time"
"github.com/VoneChain-CS/fabric-gm/internal/cryptogen/csp"
"github.com/pkg/errors"
)
type CA struct {
Name string
Country string
Province string
Locality string
OrganizationalUnit string
StreetAddress string
PostalCode string
Signer crypto.Signer
SignCert *x509.Certificate
SignSm2Cert *sm2.Certificate
Sm2Key *sm2.PrivateKey
}
// NewCA creates an instance of CA and saves the signing key pair in
// baseDir/name
func NewCA(
baseDir,
org,
name,
country,
province,
locality,
orgUnit,
streetAddress,
postalCode string,
) (*CA, error) {
var ca *CA
err := os.MkdirAll(baseDir, 0755)
if err != nil {
return nil, err
}
priv, err := csp.GeneratePrivateKey(baseDir)
if err != nil {
return nil, err
}
template := x509Template()
//this is a CA
template.IsCA = true
template.KeyUsage |= x509.KeyUsageDigitalSignature |
x509.KeyUsageKeyEncipherment | x509.KeyUsageCertSign |
x509.KeyUsageCRLSign
template.ExtKeyUsage = []x509.ExtKeyUsage{
x509.ExtKeyUsageClientAuth,
x509.ExtKeyUsageServerAuth,
}
//set the organization for the subject
subject := subjectTemplateAdditional(country, province, locality, orgUnit, streetAddress, postalCode)
subject.Organization = []string{org}
subject.CommonName = name
template.Subject = subject
templateSm2 := gm.ParseX509Certificate2Sm2(&template)
//TODO important
templateSm2.SubjectKeyId = computeSKI(priv)
sm2PubKey := priv.PublicKey
if err != nil {
errors.Errorf("error,%v", err)
}
templateSm2.SignatureAlgorithm = sm2.SM2WithSM3
sm2Cert, err := genCertificateGMSM2(
baseDir,
name,
templateSm2,
templateSm2,
&sm2PubKey,
priv,
)
if err != nil {
return nil, err
}
ca = &CA{
Name: name,
/*Signer: &csp.ECDSASigner{
PrivateKey: priv,
},*/
Signer: priv,
Country: country,
Province: province,
Locality: locality,
OrganizationalUnit: orgUnit,
StreetAddress: streetAddress,
PostalCode: postalCode,
SignSm2Cert: sm2Cert,
Sm2Key: priv,
}
return ca, err
}
// SignCertificate creates a signed certificate based on a built-in template
// and saves it in baseDir/name
func (ca *CA) SignCertificate(
baseDir,
name string,
orgUnits,
alternateNames []string,
pub *sm2.PublicKey,
ku x509.KeyUsage,
eku []x509.ExtKeyUsage,
) (*sm2.Certificate, error) {
template := x509Template()
template.KeyUsage = ku
template.ExtKeyUsage = eku
//set the organization for the subject
subject := subjectTemplateAdditional(
ca.Country,
ca.Province,
ca.Locality,
ca.OrganizationalUnit,
ca.StreetAddress,
ca.PostalCode,
)
subject.CommonName = name
subject.OrganizationalUnit = append(subject.OrganizationalUnit, orgUnits...)
template.Subject = subject
for _, san := range alternateNames {
// try to parse as an IP address first
ip := net.ParseIP(san)
if ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, alternateNames...)
}
}
template.PublicKey = pub
templateSm2 := gm.ParseX509Certificate2Sm2(&template)
templateSm2.SignatureAlgorithm = sm2.SM2WithSM3
cert, err := genCertificateGMSM2(
baseDir,
name,
templateSm2,
ca.SignSm2Cert,
pub,
ca.Sm2Key,
)
if err != nil {
return nil, err
}
return cert, nil
}
// compute Subject Key Identifier //TODO Important
func computeSKI(privKey *sm2.PrivateKey) []byte {
// Marshall the public key
raw := elliptic.Marshal(privKey.Curve, privKey.PublicKey.X, privKey.PublicKey.Y)
// Hash it
hash := sha256.New()
hash.Write(raw)
return hash.Sum(nil)
//return hash[:]
}
// default template for X509 subject
func subjectTemplate() pkix.Name {
return pkix.Name{
Country: []string{"US"},
Locality: []string{"San Francisco"},
Province: []string{"California"},
}
}
// Additional for X509 subject
func subjectTemplateAdditional(
country,
province,
locality,
orgUnit,
streetAddress,
postalCode string,
) pkix.Name {
name := subjectTemplate()
if len(country) >= 1 {
name.Country = []string{country}
}
if len(province) >= 1 {
name.Province = []string{province}
}
if len(locality) >= 1 {
name.Locality = []string{locality}
}
if len(orgUnit) >= 1 {
name.OrganizationalUnit = []string{orgUnit}
}
if len(streetAddress) >= 1 {
name.StreetAddress = []string{streetAddress}
}
if len(postalCode) >= 1 {
name.PostalCode = []string{postalCode}
}
return name
}
// default template for X509 certificates
func x509Template() x509.Certificate {
// generate a serial number
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, _ := rand.Int(rand.Reader, serialNumberLimit)
// set expiry to around 10 years
expiry := 3650 * 24 * time.Hour
// round minute and backdate 5 minutes TODO
notBefore := time.Now().Add(-5 * time.Minute).UTC()
//basic template to use
x509 := x509.Certificate{
SerialNumber: serialNumber,
NotBefore: notBefore,
NotAfter: notBefore.Add(expiry).UTC(),
BasicConstraintsValid: true,
}
return x509
}
// generate a signed X509 certificate using ECDSA
func genCertificateECDSA(
baseDir,
name string,
template,
parent *x509.Certificate,
pub *ecdsa.PublicKey,
priv interface{},
) (*x509.Certificate, error) {
//create the x509 public cert
certBytes, err := x509.CreateCertificate(rand.Reader, template, parent, pub, priv)
if err != nil {
return nil, err
}
//write cert out to file
fileName := filepath.Join(baseDir, name+"-cert.pem")
certFile, err := os.Create(fileName)
if err != nil {
return nil, err
}
//pem encode the cert
err = pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: certBytes})
certFile.Close()
if err != nil {
return nil, err
}
x509Cert, err := x509.ParseCertificate(certBytes)
if err != nil {
return nil, err
}
return x509Cert, nil
}
//generate a signed X509 certficate using GMSM2
func genCertificateGMSM21(
baseDir,
name string,
template, parent *sm2.Certificate,
pub *sm2.PublicKey,
key bccsp.Key) (*sm2.Certificate, error) {
//create the x509 public cert
certBytes, err := gm.CreateCertificateToMem(template, parent, key)
if err != nil {
return nil, err
}
//write cert out to file
fileName := filepath.Join(baseDir, name+"-cert.pem")
err = ioutil.WriteFile(fileName, certBytes, os.FileMode(0666))
// certFile, err := os.Create(fileName)
if err != nil {
return nil, err
}
// //pem encode the cert
// err = pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: certBytes})
// certFile.Close()
// if err != nil {
// return nil, err
// }
//x509Cert, err := sm2.ReadCertificateFromPem(fileName)
x509Cert, err := sm2.ReadCertificateFromMem(certBytes)
if err != nil {
return nil, err
}
return x509Cert, nil
}
// TODO generate a signed sm2 certificate using SM2
func genCertificateGMSM2(
baseDir,
name string,
template,
parent *sm2.Certificate,
pub *sm2.PublicKey,
priv interface{},
) (*sm2.Certificate, error) {
//create the x509 public cert
certBytes, err := sm2.CreateCertificate(rand.Reader, template, parent, pub, priv)
if err != nil {
return nil, err
}
//write cert out to file
fileName := filepath.Join(baseDir, name+"-cert.pem")
certFile, err := os.Create(fileName)
if err != nil {
return nil, err
}
//pem encode the cert
err = pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: certBytes})
certFile.Close()
if err != nil {
return nil, err
}
x509Cert, err := sm2.ParseCertificate(certBytes)
if err != nil {
return nil, err
}
return x509Cert, nil
}
// LoadCertificateECDSA load a ecdsa cert from a file in cert path
func LoadCertificateECDSA(certPath string) (*x509.Certificate, error) {
var cert *x509.Certificate
var err error
walkFunc := func(path string, info os.FileInfo, err error) error {
if strings.HasSuffix(path, ".pem") {
rawCert, err := ioutil.ReadFile(path)
if err != nil {
return err
}
block, _ := pem.Decode(rawCert)
if block == nil || block.Type != "CERTIFICATE" {
return errors.Errorf("%s: wrong PEM encoding", path)
}
cert, err = x509.ParseCertificate(block.Bytes)
if err != nil {
return errors.Errorf("%s: wrong DER encoding", path)
}
}
return nil
}
err = filepath.Walk(certPath, walkFunc)
if err != nil {
return nil, err
}
return cert, err
}
// LoadCertificateGMSM2 load a ecdsa cert from a file in cert path
func LoadCertificateGMSM2(certPath string) (*sm2.Certificate, error) {
var cert *sm2.Certificate
var err error
walkFunc := func(path string, info os.FileInfo, err error) error {
if strings.HasSuffix(path, ".pem") {
rawCert, err := ioutil.ReadFile(path)
if err != nil {
return err
}
block, _ := pem.Decode(rawCert)
if block == nil || block.Type != "CERTIFICATE" {
return errors.Errorf("%s: wrong PEM encoding", path)
}
cert, err = sm2.ParseCertificate(block.Bytes)
if err != nil {
return errors.Errorf("%s: wrong DER encoding", path)
}
}
return nil
}
err = filepath.Walk(certPath, walkFunc)
if err != nil {
return nil, err
}
return cert, err
}