github.com/outbrain/consul@v1.4.5/agent/connect/generate.go (about)

     1  package connect
     2  
     3  import (
     4  	"bytes"
     5  	"crypto"
     6  	"crypto/ecdsa"
     7  	"crypto/elliptic"
     8  	"crypto/rand"
     9  	"crypto/x509"
    10  	"encoding/pem"
    11  	"fmt"
    12  )
    13  
    14  // GeneratePrivateKey generates a new Private key
    15  func GeneratePrivateKey() (crypto.Signer, string, error) {
    16  	var pk *ecdsa.PrivateKey
    17  
    18  	pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
    19  	if err != nil {
    20  		return nil, "", fmt.Errorf("error generating private key: %s", err)
    21  	}
    22  
    23  	bs, err := x509.MarshalECPrivateKey(pk)
    24  	if err != nil {
    25  		return nil, "", fmt.Errorf("error generating private key: %s", err)
    26  	}
    27  
    28  	var buf bytes.Buffer
    29  	err = pem.Encode(&buf, &pem.Block{Type: "EC PRIVATE KEY", Bytes: bs})
    30  	if err != nil {
    31  		return nil, "", fmt.Errorf("error encoding private key: %s", err)
    32  	}
    33  
    34  	return pk, buf.String(), nil
    35  }