/
crypto.go
72 lines (63 loc) · 2.69 KB
/
crypto.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
/*******************************************************************************
* Copyright 2019 Dell Inc.
*
* Licensed 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 certificates
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"fmt"
"github.com/edgexfoundry/edgex-go/internal/security/secrets/seed"
"github.com/edgexfoundry/go-mod-core-contracts/clients/logger"
)
// generatePrivateKey creates a new RSA or EC based private key (sk)
// ----------------------------------------------------------
func generatePrivateKey(certificateSeed seed.CertificateSeed, logger logger.LoggingClient) (crypto.PrivateKey, error) {
if certificateSeed.RSAScheme {
logger.Debug(fmt.Sprintf("Generating private key with RSA scheme %v", certificateSeed.RSAKeySize))
return rsa.GenerateKey(rand.Reader, int(certificateSeed.RSAKeySize))
}
if certificateSeed.ECScheme {
logger.Debug(fmt.Sprintf("Generating private key with EC scheme %v", certificateSeed.ECCurve))
switch certificateSeed.ECCurve {
case seed.EC_224: // secp224r1 NIST P-224
return ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
case seed.EC_256: // secp256v1 NIST P-256
return ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
case seed.EC_384: // secp384r1 NIST P-384
return ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
case seed.EC_521: // secp521r1 NIST P-521
return ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
}
}
return nil, fmt.Errorf("Unknown key scheme: RSA[%t] EC[%t]", certificateSeed.RSAScheme, certificateSeed.ECScheme)
}
// dumpKeyPair output sk,pk keypair (RSA or EC) to console
// !!! Debug only for obvious security reasons...
// ----------------------------------------------------------
func dumpKeyPair(key interface{}, logger logger.LoggingClient) {
switch key.(type) {
case *rsa.PrivateKey:
logger.Debug(fmt.Sprintf(">> RSA SK: %q", key))
case *ecdsa.PrivateKey:
logger.Debug(fmt.Sprintf(">> ECDSA SK: %q", key))
case *rsa.PublicKey:
logger.Debug(fmt.Sprintf(">> RSA PK: %q", key))
case *ecdsa.PublicKey:
logger.Debug(fmt.Sprintf(">> ECDSA PK: %q", key))
default:
logger.Error("Unsupported Key Type")
}
}