github.com/trustbloc/kms-go@v1.1.2/crypto/eckey.go (about)

     1  /*
     2  Copyright SecureKey Technologies Inc. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package crypto
     8  
     9  import (
    10  	"crypto/ecdsa"
    11  	"crypto/elliptic"
    12  	"fmt"
    13  	"math/big"
    14  
    15  	"github.com/trustbloc/kms-go/spi/crypto"
    16  )
    17  
    18  // ToECKey converts key to an ecdsa public key. It returns an error if the curve is invalid.
    19  func ToECKey(key *crypto.PublicKey) (*ecdsa.PublicKey, error) {
    20  	crv, err := toCurve(key.Curve)
    21  	if err != nil {
    22  		return nil, err
    23  	}
    24  
    25  	return &ecdsa.PublicKey{
    26  		Curve: crv,
    27  		X:     new(big.Int).SetBytes(key.X),
    28  		Y:     new(big.Int).SetBytes(key.Y),
    29  	}, nil
    30  }
    31  
    32  func toCurve(crv string) (elliptic.Curve, error) {
    33  	switch crv {
    34  	case "P-256", "NIST_P256":
    35  		return elliptic.P256(), nil
    36  	case "P-384", "NIST_P384":
    37  		return elliptic.P384(), nil
    38  	case "P-521", "NIST_P521":
    39  		return elliptic.P521(), nil
    40  	}
    41  
    42  	return nil, fmt.Errorf("invalid curve '%s'", crv)
    43  }