-
Notifications
You must be signed in to change notification settings - Fork 6
/
generate.go
95 lines (75 loc) · 2.56 KB
/
generate.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
package crypto
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"fmt"
"github.com/coinbase/baseca/pkg/types"
)
type CSRGenerator interface {
Generate() (crypto.PrivateKey, error)
KeyType() string
MarshalPrivateKey(key crypto.PrivateKey) ([]byte, error)
SupportsPublicKeyAlgorithm(algorithm x509.PublicKeyAlgorithm) bool
SupportsSigningAlgorithm(algorithm x509.SignatureAlgorithm) bool
SupportsKeySize(size int) bool
}
type SigningRequestGeneratorRSA struct {
Size int
}
type SigningRequestGeneratorECDSA struct {
Curve int
}
// RSA Interface
func (r *SigningRequestGeneratorRSA) Generate() (crypto.PrivateKey, error) {
return rsa.GenerateKey(rand.Reader, r.Size)
}
func (r *SigningRequestGeneratorRSA) KeyType() string {
return types.RSA_PRIVATE_KEY.String()
}
func (r *SigningRequestGeneratorRSA) MarshalPrivateKey(key crypto.PrivateKey) ([]byte, error) {
return x509.MarshalPKCS1PrivateKey(key.(*rsa.PrivateKey)), nil
}
func (r *SigningRequestGeneratorRSA) SupportsPublicKeyAlgorithm(algorithm x509.PublicKeyAlgorithm) bool {
return algorithm == x509.RSA
}
func (r *SigningRequestGeneratorRSA) SupportsSigningAlgorithm(algorithm x509.SignatureAlgorithm) bool {
_, ok := types.PublicKeyAlgorithms[types.RSA].SigningAlgorithm[algorithm]
return ok
}
func (r *SigningRequestGeneratorRSA) SupportsKeySize(size int) bool {
_, ok := types.PublicKeyAlgorithms[types.RSA].KeySize[size]
return ok
}
// ECDSA Interface
func (e *SigningRequestGeneratorECDSA) Generate() (crypto.PrivateKey, error) {
c, ok := types.PublicKeyAlgorithms[types.ECDSA].KeySize[e.Curve]
if !ok {
return nil, fmt.Errorf("ecdsa curve [%d] not supported", e.Curve)
}
curve, ok := c.(elliptic.Curve)
if !ok {
return nil, fmt.Errorf("invalid elliptic.Curve type")
}
return ecdsa.GenerateKey(curve, rand.Reader)
}
func (e *SigningRequestGeneratorECDSA) KeyType() string {
return types.ECDSA_PRIVATE_KEY.String()
}
func (e *SigningRequestGeneratorECDSA) MarshalPrivateKey(key crypto.PrivateKey) ([]byte, error) {
return x509.MarshalECPrivateKey(key.(*ecdsa.PrivateKey))
}
func (e *SigningRequestGeneratorECDSA) SupportsPublicKeyAlgorithm(algorithm x509.PublicKeyAlgorithm) bool {
return algorithm == x509.ECDSA
}
func (e *SigningRequestGeneratorECDSA) SupportsSigningAlgorithm(algorithm x509.SignatureAlgorithm) bool {
_, ok := types.PublicKeyAlgorithms[types.ECDSA].SigningAlgorithm[algorithm]
return ok
}
func (e *SigningRequestGeneratorECDSA) SupportsKeySize(size int) bool {
_, ok := types.PublicKeyAlgorithms[types.ECDSA].KeySize[size]
return ok
}