This repository has been archived by the owner on Mar 6, 2024. It is now read-only.
forked from s7techlab/hlf-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 2
/
enroll.go
87 lines (68 loc) · 2.47 KB
/
enroll.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
package ca
import (
"bytes"
"context"
"crypto/rand"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"net/http"
"github.com/cloudflare/cfssl/signer"
"github.com/pkg/errors"
"github.com/atomyze-ru/hlf-sdk-go/api/ca"
)
const enrollEndpoint = `/api/v1/enroll`
func (c *core) Enroll(ctx context.Context, name, secret string, req *x509.CertificateRequest, opts ...ca.EnrollOpt) (*x509.Certificate, interface{}, error) {
var err error
options := &ca.EnrollOpts{}
for _, opt := range opts {
if err = opt(options); err != nil {
return nil, nil, errors.Wrap(err, `failed to apply option`)
}
}
if options.PrivateKey == nil {
if options.PrivateKey, err = c.cs.NewPrivateKey(); err != nil {
return nil, nil, errors.Wrap(err, `failed to generate private key`)
}
}
// Add default signature algorithm if not defined
if req.SignatureAlgorithm == x509.UnknownSignatureAlgorithm {
req.SignatureAlgorithm = c.cs.GetSignatureAlgorithm()
}
csr, err := x509.CreateCertificateRequest(rand.Reader, req, options.PrivateKey)
if err != nil {
return nil, options.PrivateKey, errors.Wrap(err, `failed to get certificate request`)
}
pemCsr := pem.EncodeToMemory(&pem.Block{Type: `CERTIFICATE REQUEST`, Bytes: csr})
reqBytes, err := json.Marshal(signer.SignRequest{Request: string(pemCsr)})
if err != nil {
return nil, options.PrivateKey, errors.Wrap(err, `failed to marshal CSR request to JSON`)
}
httpReq, err := http.NewRequest(http.MethodPost, c.config.Host+enrollEndpoint, bytes.NewBuffer(reqBytes))
if err != nil {
return nil, options.PrivateKey, errors.Wrap(err, `failed to create http request`)
}
httpReq.SetBasicAuth(name, secret)
resp, err := c.client.Do(httpReq.WithContext(ctx))
if err != nil {
return nil, options.PrivateKey, errors.Wrap(err, `failed to send http request`)
}
var enrollResp ca.ResponseEnrollment
if err = c.processResponse(resp, &enrollResp, http.StatusCreated); err != nil {
return nil, options.PrivateKey, err
}
certDecoded, err := base64.StdEncoding.DecodeString(enrollResp.Cert)
if err != nil {
return nil, options.PrivateKey, errors.Wrap(err, `failed to decode base64 certificate`)
}
certBlock, _ := pem.Decode(certDecoded)
if certBlock == nil {
return nil, options.PrivateKey, errors.New(`failed to decode PEM block`)
}
cert, err := x509.ParseCertificate(certBlock.Bytes)
if err != nil {
return nil, options.PrivateKey, errors.Wrap(err, `failed to parse certificate`)
}
return cert, options.PrivateKey, nil
}