makeKey generates an RSA or ECDSA private key using the configuration in 'c'. The new private key is stored in the path at 'keyFile'. If force is true, any existing file at the path is replaced. For RSA, the configuration keySize is used for length. For ECDSA, the configuration elliptical curve is u
(keyFile string, c *certConfig)
| 41 | // For ECDSA, the configuration elliptical curve is used. |
| 42 | // Returns the RSA or ECDSA private key, or error otherwise. |
| 43 | func makeKey(keyFile string, c *certConfig) (crypto.PrivateKey, error) { |
| 44 | fp, err := safeCreate(keyFile, c.force, 0600) |
| 45 | if err != nil { |
| 46 | // reuse the existing key, if possible. |
| 47 | if os.IsExist(err) { |
| 48 | return readKey(keyFile) |
| 49 | } |
| 50 | return nil, err |
| 51 | } |
| 52 | defer func() { |
| 53 | if err := fp.Close(); err != nil { |
| 54 | glog.Warningf("error closing file: %v", err) |
| 55 | } |
| 56 | }() |
| 57 | |
| 58 | var key crypto.PrivateKey |
| 59 | switch c.curve { |
| 60 | case "": |
| 61 | key, err = rsa.GenerateKey(rand.Reader, c.keySize) |
| 62 | case "P224": |
| 63 | key, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader) |
| 64 | case "P256": |
| 65 | key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| 66 | case "P384": |
| 67 | key, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader) |
| 68 | case "P521": |
| 69 | key, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader) |
| 70 | } |
| 71 | if err != nil { |
| 72 | return nil, err |
| 73 | } |
| 74 | |
| 75 | switch k := key.(type) { |
| 76 | case *ecdsa.PrivateKey: |
| 77 | b, err := x509.MarshalECPrivateKey(k) |
| 78 | if err != nil { |
| 79 | return nil, err |
| 80 | } |
| 81 | return key, pem.Encode(fp, &pem.Block{ |
| 82 | Type: "EC PRIVATE KEY", |
| 83 | Bytes: b, |
| 84 | }) |
| 85 | case *rsa.PrivateKey: |
| 86 | return key, pem.Encode(fp, &pem.Block{ |
| 87 | Type: "RSA PRIVATE KEY", |
| 88 | Bytes: x509.MarshalPKCS1PrivateKey(k), |
| 89 | }) |
| 90 | } |
| 91 | return nil, errors.Errorf("Unsupported key type: %T", key) |
| 92 | } |
| 93 | |
| 94 | // readKey tries to read and decode the contents of a private key file. |
| 95 | // Returns the private key, or error otherwise. |
no test coverage detected