consul/agent/connect/generate.go

36 lines
769 B
Go
Raw Normal View History

2018-05-09 22:12:31 +00:00
package connect
import (
"bytes"
2018-05-12 10:58:14 +00:00
"crypto"
2018-05-09 22:12:31 +00:00
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
)
2018-05-12 10:58:14 +00:00
// GeneratePrivateKey generates a new Private key
func GeneratePrivateKey() (crypto.Signer, string, error) {
2018-05-09 22:12:31 +00:00
var pk *ecdsa.PrivateKey
pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
2018-05-12 10:58:14 +00:00
return nil, "", fmt.Errorf("error generating private key: %s", err)
2018-05-09 22:12:31 +00:00
}
bs, err := x509.MarshalECPrivateKey(pk)
if err != nil {
2018-05-12 10:58:14 +00:00
return nil, "", fmt.Errorf("error generating private key: %s", err)
2018-05-09 22:12:31 +00:00
}
var buf bytes.Buffer
err = pem.Encode(&buf, &pem.Block{Type: "EC PRIVATE KEY", Bytes: bs})
if err != nil {
2018-05-12 10:58:14 +00:00
return nil, "", fmt.Errorf("error encoding private key: %s", err)
2018-05-09 22:12:31 +00:00
}
2018-05-12 10:58:14 +00:00
return pk, buf.String(), nil
2018-05-09 22:12:31 +00:00
}