github.com/trustbloc/kms-go@v1.1.2/crypto/eckey_test.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  	"crypto/rand"
    13  	"testing"
    14  
    15  	"github.com/stretchr/testify/require"
    16  
    17  	"github.com/trustbloc/kms-go/spi/crypto"
    18  )
    19  
    20  func TestToECKey(t *testing.T) {
    21  	tests := []struct {
    22  		name  string
    23  		curve elliptic.Curve
    24  	}{
    25  		{
    26  			name:  "to P-256 key",
    27  			curve: elliptic.P256(),
    28  		},
    29  		{
    30  			name:  "to P-384 key",
    31  			curve: elliptic.P384(),
    32  		},
    33  		{
    34  			name:  "to P-521 key",
    35  			curve: elliptic.P521(),
    36  		},
    37  		{
    38  			name:  "invalid curve",
    39  			curve: nil,
    40  		},
    41  	}
    42  
    43  	for _, tt := range tests {
    44  		tc := tt
    45  		t.Run(tc.name, func(t *testing.T) {
    46  			if tc.name == "invalid curve" {
    47  				_, err := ToECKey(&crypto.PublicKey{
    48  					Curve: "undefined",
    49  					Type:  "EC",
    50  				})
    51  				require.EqualError(t, err, "invalid curve 'undefined'")
    52  
    53  				return
    54  			}
    55  
    56  			privKey, err := ecdsa.GenerateKey(tc.curve, rand.Reader)
    57  			require.NoError(t, err)
    58  
    59  			pubKey := &crypto.PublicKey{
    60  				X:     privKey.X.Bytes(),
    61  				Y:     privKey.Y.Bytes(),
    62  				Curve: tc.curve.Params().Name,
    63  				Type:  "EC",
    64  			}
    65  
    66  			pubECKey, err := ToECKey(pubKey)
    67  			require.NoError(t, err)
    68  			require.Equal(t, tc.curve.Params().Name, pubECKey.Curve.Params().Name)
    69  			require.EqualValues(t, privKey.X.Bytes(), pubECKey.X.Bytes())
    70  			require.EqualValues(t, privKey.Y.Bytes(), pubECKey.Y.Bytes())
    71  		})
    72  	}
    73  }