github.com/hairyhenderson/gomplate/v3@v3.11.7/crypto/ecdsa.go (about)

     1  package crypto
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/ecdsa"
     6  	"crypto/elliptic"
     7  	"crypto/rand"
     8  	"crypto/x509"
     9  	"encoding/pem"
    10  	"fmt"
    11  )
    12  
    13  // Curves is a map of curve names to curves
    14  var Curves = map[string]elliptic.Curve{
    15  	"P224": elliptic.P224(),
    16  	"P256": elliptic.P256(),
    17  	"P384": elliptic.P384(),
    18  	"P521": elliptic.P521(),
    19  }
    20  
    21  // ECDSAGenerateKey -
    22  func ECDSAGenerateKey(curve elliptic.Curve) ([]byte, error) {
    23  	priv, err := ecdsa.GenerateKey(curve, rand.Reader)
    24  	if err != nil {
    25  		return nil, fmt.Errorf("failed to generate ECDSA private key: %w", err)
    26  	}
    27  
    28  	der, err := x509.MarshalECPrivateKey(priv)
    29  	if err != nil {
    30  		return nil, fmt.Errorf("failed to marshal ECDSA private key: %w", err)
    31  	}
    32  
    33  	block := &pem.Block{
    34  		Type:  "EC PRIVATE KEY",
    35  		Bytes: der,
    36  	}
    37  	buf := &bytes.Buffer{}
    38  
    39  	err = pem.Encode(buf, block)
    40  	if err != nil {
    41  		return nil, fmt.Errorf("failed to encode generated ECDSA private key: pem encoding failed: %w", err)
    42  	}
    43  
    44  	return buf.Bytes(), nil
    45  }
    46  
    47  // ECDSADerivePublicKey -
    48  func ECDSADerivePublicKey(privatekey []byte) ([]byte, error) {
    49  	block, _ := pem.Decode(privatekey)
    50  	if block == nil {
    51  		return nil, fmt.Errorf("failed to read key: no key found")
    52  	}
    53  
    54  	priv, err := x509.ParseECPrivateKey(block.Bytes)
    55  	if err != nil {
    56  		return nil, fmt.Errorf("invalid private key: %w", err)
    57  	}
    58  
    59  	b, err := x509.MarshalPKIXPublicKey(&priv.PublicKey)
    60  	if err != nil {
    61  		return nil, fmt.Errorf("failed to marshal PKIX public key: %w", err)
    62  	}
    63  
    64  	block = &pem.Block{
    65  		Type:  "PUBLIC KEY",
    66  		Bytes: b,
    67  	}
    68  
    69  	return pem.EncodeToMemory(block), nil
    70  }