forked from adamlaska/boulder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkey.go
More file actions
87 lines (75 loc) · 2.29 KB
/
key.go
File metadata and controls
87 lines (75 loc) · 2.29 KB
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 notmain
import (
"crypto"
"crypto/x509"
"encoding/pem"
"fmt"
"log"
"github.com/letsencrypt/boulder/pkcs11helpers"
"github.com/miekg/pkcs11"
)
type hsmRandReader struct {
*pkcs11helpers.Session
}
func newRandReader(session *pkcs11helpers.Session) *hsmRandReader {
return &hsmRandReader{session}
}
func (hrr hsmRandReader) Read(p []byte) (n int, err error) {
r, err := hrr.Module.GenerateRandom(hrr.Session.Session, len(p))
if err != nil {
return 0, err
}
copy(p[:], r)
return len(r), nil
}
type generateArgs struct {
mechanism []*pkcs11.Mechanism
privateAttrs []*pkcs11.Attribute
publicAttrs []*pkcs11.Attribute
}
const (
rsaExp = 65537
)
// keyInfo is a struct used to pass around information about the public key
// associated with the generated private key. der contains the DER encoding
// of the SubjectPublicKeyInfo structure for the public key. id contains the
// HSM key pair object ID.
type keyInfo struct {
key crypto.PublicKey
der []byte
id []byte
}
func generateKey(session *pkcs11helpers.Session, label string, outputPath string, config keyGenConfig) (*keyInfo, error) {
_, err := session.FindObject([]*pkcs11.Attribute{
{Type: pkcs11.CKA_LABEL, Value: []byte(label)},
})
if err != pkcs11helpers.ErrNoObject {
return nil, fmt.Errorf("expected no preexisting objects with label %q in slot for key storage. got error: %s", label, err)
}
var pubKey crypto.PublicKey
var keyID []byte
switch config.Type {
case "rsa":
pubKey, keyID, err = rsaGenerate(session, label, config.RSAModLength, rsaExp)
if err != nil {
return nil, fmt.Errorf("failed to generate RSA key pair: %s", err)
}
case "ecdsa":
pubKey, keyID, err = ecGenerate(session, label, config.ECDSACurve)
if err != nil {
return nil, fmt.Errorf("failed to generate ECDSA key pair: %s", err)
}
}
der, err := x509.MarshalPKIXPublicKey(pubKey)
if err != nil {
return nil, fmt.Errorf("Failed to marshal public key: %s", err)
}
pemBytes := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: der})
log.Printf("Public key PEM:\n%s\n", pemBytes)
err = writeFile(outputPath, pemBytes)
if err != nil {
return nil, fmt.Errorf("Failed to write public key to %q: %s", outputPath, err)
}
log.Printf("Public key written to %q\n", outputPath)
return &keyInfo{key: pubKey, der: der, id: keyID}, nil
}