github.com/googgoog/go-ethereum@v1.9.7/crypto/ecies/ecies_test.go (about)

     1  // Copyright (c) 2013 Kyle Isom <kyle@tyrfingr.is>
     2  // Copyright (c) 2012 The Go Authors. All rights reserved.
     3  //
     4  // Redistribution and use in source and binary forms, with or without
     5  // modification, are permitted provided that the following conditions are
     6  // met:
     7  //
     8  //    * Redistributions of source code must retain the above copyright
     9  // notice, this list of conditions and the following disclaimer.
    10  //    * Redistributions in binary form must reproduce the above
    11  // copyright notice, this list of conditions and the following disclaimer
    12  // in the documentation and/or other materials provided with the
    13  // distribution.
    14  //    * Neither the name of Google Inc. nor the names of its
    15  // contributors may be used to endorse or promote products derived from
    16  // this software without specific prior written permission.
    17  //
    18  // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    19  // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    20  // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    21  // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    22  // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    23  // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    24  // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    25  // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    26  // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    27  // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    28  // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    29  
    30  package ecies
    31  
    32  import (
    33  	"bytes"
    34  	"crypto/elliptic"
    35  	"crypto/rand"
    36  	"crypto/sha256"
    37  	"encoding/hex"
    38  	"fmt"
    39  	"math/big"
    40  	"testing"
    41  
    42  	"github.com/ethereum/go-ethereum/crypto"
    43  )
    44  
    45  // Ensure the KDF generates appropriately sized keys.
    46  func TestKDF(t *testing.T) {
    47  	msg := []byte("Hello, world")
    48  	h := sha256.New()
    49  
    50  	k, err := concatKDF(h, msg, nil, 64)
    51  	if err != nil {
    52  		t.Fatal(err)
    53  	}
    54  	if len(k) != 64 {
    55  		t.Fatalf("KDF: generated key is the wrong size (%d instead of 64\n", len(k))
    56  	}
    57  }
    58  
    59  var ErrBadSharedKeys = fmt.Errorf("ecies: shared keys don't match")
    60  
    61  // cmpParams compares a set of ECIES parameters. We assume, as per the
    62  // docs, that AES is the only supported symmetric encryption algorithm.
    63  func cmpParams(p1, p2 *ECIESParams) bool {
    64  	return p1.hashAlgo == p2.hashAlgo &&
    65  		p1.KeyLen == p2.KeyLen &&
    66  		p1.BlockSize == p2.BlockSize
    67  }
    68  
    69  // cmpPublic returns true if the two public keys represent the same pojnt.
    70  func cmpPublic(pub1, pub2 PublicKey) bool {
    71  	if pub1.X == nil || pub1.Y == nil {
    72  		fmt.Println(ErrInvalidPublicKey.Error())
    73  		return false
    74  	}
    75  	if pub2.X == nil || pub2.Y == nil {
    76  		fmt.Println(ErrInvalidPublicKey.Error())
    77  		return false
    78  	}
    79  	pub1Out := elliptic.Marshal(pub1.Curve, pub1.X, pub1.Y)
    80  	pub2Out := elliptic.Marshal(pub2.Curve, pub2.X, pub2.Y)
    81  
    82  	return bytes.Equal(pub1Out, pub2Out)
    83  }
    84  
    85  // Validate the ECDH component.
    86  func TestSharedKey(t *testing.T) {
    87  	prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil)
    88  	if err != nil {
    89  		t.Fatal(err)
    90  	}
    91  	skLen := MaxSharedKeyLength(&prv1.PublicKey) / 2
    92  
    93  	prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil)
    94  	if err != nil {
    95  		t.Fatal(err)
    96  	}
    97  
    98  	sk1, err := prv1.GenerateShared(&prv2.PublicKey, skLen, skLen)
    99  	if err != nil {
   100  		t.Fatal(err)
   101  	}
   102  
   103  	sk2, err := prv2.GenerateShared(&prv1.PublicKey, skLen, skLen)
   104  	if err != nil {
   105  		t.Fatal(err)
   106  	}
   107  
   108  	if !bytes.Equal(sk1, sk2) {
   109  		t.Fatal(ErrBadSharedKeys)
   110  	}
   111  }
   112  
   113  func TestSharedKeyPadding(t *testing.T) {
   114  	// sanity checks
   115  	prv0 := hexKey("1adf5c18167d96a1f9a0b1ef63be8aa27eaf6032c233b2b38f7850cf5b859fd9")
   116  	prv1 := hexKey("0097a076fc7fcd9208240668e31c9abee952cbb6e375d1b8febc7499d6e16f1a")
   117  	x0, _ := new(big.Int).SetString("1a8ed022ff7aec59dc1b440446bdda5ff6bcb3509a8b109077282b361efffbd8", 16)
   118  	x1, _ := new(big.Int).SetString("6ab3ac374251f638d0abb3ef596d1dc67955b507c104e5f2009724812dc027b8", 16)
   119  	y0, _ := new(big.Int).SetString("e040bd480b1deccc3bc40bd5b1fdcb7bfd352500b477cb9471366dbd4493f923", 16)
   120  	y1, _ := new(big.Int).SetString("8ad915f2b503a8be6facab6588731fefeb584fd2dfa9a77a5e0bba1ec439e4fa", 16)
   121  
   122  	if prv0.PublicKey.X.Cmp(x0) != 0 {
   123  		t.Errorf("mismatched prv0.X:\nhave: %x\nwant: %x\n", prv0.PublicKey.X.Bytes(), x0.Bytes())
   124  	}
   125  	if prv0.PublicKey.Y.Cmp(y0) != 0 {
   126  		t.Errorf("mismatched prv0.Y:\nhave: %x\nwant: %x\n", prv0.PublicKey.Y.Bytes(), y0.Bytes())
   127  	}
   128  	if prv1.PublicKey.X.Cmp(x1) != 0 {
   129  		t.Errorf("mismatched prv1.X:\nhave: %x\nwant: %x\n", prv1.PublicKey.X.Bytes(), x1.Bytes())
   130  	}
   131  	if prv1.PublicKey.Y.Cmp(y1) != 0 {
   132  		t.Errorf("mismatched prv1.Y:\nhave: %x\nwant: %x\n", prv1.PublicKey.Y.Bytes(), y1.Bytes())
   133  	}
   134  
   135  	// test shared secret generation
   136  	sk1, err := prv0.GenerateShared(&prv1.PublicKey, 16, 16)
   137  	if err != nil {
   138  		t.Log(err.Error())
   139  	}
   140  
   141  	sk2, err := prv1.GenerateShared(&prv0.PublicKey, 16, 16)
   142  	if err != nil {
   143  		t.Fatal(err.Error())
   144  	}
   145  
   146  	if !bytes.Equal(sk1, sk2) {
   147  		t.Fatal(ErrBadSharedKeys.Error())
   148  	}
   149  }
   150  
   151  // Verify that the key generation code fails when too much key data is
   152  // requested.
   153  func TestTooBigSharedKey(t *testing.T) {
   154  	prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   155  	if err != nil {
   156  		t.Fatal(err)
   157  	}
   158  
   159  	prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   160  	if err != nil {
   161  		t.Fatal(err)
   162  	}
   163  
   164  	_, err = prv1.GenerateShared(&prv2.PublicKey, 32, 32)
   165  	if err != ErrSharedKeyTooBig {
   166  		t.Fatal("ecdh: shared key should be too large for curve")
   167  	}
   168  
   169  	_, err = prv2.GenerateShared(&prv1.PublicKey, 32, 32)
   170  	if err != ErrSharedKeyTooBig {
   171  		t.Fatal("ecdh: shared key should be too large for curve")
   172  	}
   173  }
   174  
   175  // Benchmark the generation of P256 keys.
   176  func BenchmarkGenerateKeyP256(b *testing.B) {
   177  	for i := 0; i < b.N; i++ {
   178  		if _, err := GenerateKey(rand.Reader, elliptic.P256(), nil); err != nil {
   179  			b.Fatal(err)
   180  		}
   181  	}
   182  }
   183  
   184  // Benchmark the generation of P256 shared keys.
   185  func BenchmarkGenSharedKeyP256(b *testing.B) {
   186  	prv, err := GenerateKey(rand.Reader, elliptic.P256(), nil)
   187  	if err != nil {
   188  		b.Fatal(err)
   189  	}
   190  	b.ResetTimer()
   191  	for i := 0; i < b.N; i++ {
   192  		_, err := prv.GenerateShared(&prv.PublicKey, 16, 16)
   193  		if err != nil {
   194  			b.Fatal(err)
   195  		}
   196  	}
   197  }
   198  
   199  // Benchmark the generation of S256 shared keys.
   200  func BenchmarkGenSharedKeyS256(b *testing.B) {
   201  	prv, err := GenerateKey(rand.Reader, crypto.S256(), nil)
   202  	if err != nil {
   203  		b.Fatal(err)
   204  	}
   205  	b.ResetTimer()
   206  	for i := 0; i < b.N; i++ {
   207  		_, err := prv.GenerateShared(&prv.PublicKey, 16, 16)
   208  		if err != nil {
   209  			b.Fatal(err)
   210  		}
   211  	}
   212  }
   213  
   214  // Verify that an encrypted message can be successfully decrypted.
   215  func TestEncryptDecrypt(t *testing.T) {
   216  	prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   217  	if err != nil {
   218  		t.Fatal(err)
   219  	}
   220  
   221  	prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   222  	if err != nil {
   223  		t.Fatal(err)
   224  	}
   225  
   226  	message := []byte("Hello, world.")
   227  	ct, err := Encrypt(rand.Reader, &prv2.PublicKey, message, nil, nil)
   228  	if err != nil {
   229  		t.Fatal(err)
   230  	}
   231  
   232  	pt, err := prv2.Decrypt(ct, nil, nil)
   233  	if err != nil {
   234  		t.Fatal(err)
   235  	}
   236  
   237  	if !bytes.Equal(pt, message) {
   238  		t.Fatal("ecies: plaintext doesn't match message")
   239  	}
   240  
   241  	_, err = prv1.Decrypt(ct, nil, nil)
   242  	if err == nil {
   243  		t.Fatal("ecies: encryption should not have succeeded")
   244  	}
   245  }
   246  
   247  func TestDecryptShared2(t *testing.T) {
   248  	prv, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   249  	if err != nil {
   250  		t.Fatal(err)
   251  	}
   252  	message := []byte("Hello, world.")
   253  	shared2 := []byte("shared data 2")
   254  	ct, err := Encrypt(rand.Reader, &prv.PublicKey, message, nil, shared2)
   255  	if err != nil {
   256  		t.Fatal(err)
   257  	}
   258  
   259  	// Check that decrypting with correct shared data works.
   260  	pt, err := prv.Decrypt(ct, nil, shared2)
   261  	if err != nil {
   262  		t.Fatal(err)
   263  	}
   264  	if !bytes.Equal(pt, message) {
   265  		t.Fatal("ecies: plaintext doesn't match message")
   266  	}
   267  
   268  	// Decrypting without shared data or incorrect shared data fails.
   269  	if _, err = prv.Decrypt(ct, nil, nil); err == nil {
   270  		t.Fatal("ecies: decrypting without shared data didn't fail")
   271  	}
   272  	if _, err = prv.Decrypt(ct, nil, []byte("garbage")); err == nil {
   273  		t.Fatal("ecies: decrypting with incorrect shared data didn't fail")
   274  	}
   275  }
   276  
   277  type testCase struct {
   278  	Curve    elliptic.Curve
   279  	Name     string
   280  	Expected *ECIESParams
   281  }
   282  
   283  var testCases = []testCase{
   284  	{
   285  		Curve:    elliptic.P256(),
   286  		Name:     "P256",
   287  		Expected: ECIES_AES128_SHA256,
   288  	},
   289  	{
   290  		Curve:    elliptic.P384(),
   291  		Name:     "P384",
   292  		Expected: ECIES_AES256_SHA384,
   293  	},
   294  	{
   295  		Curve:    elliptic.P521(),
   296  		Name:     "P521",
   297  		Expected: ECIES_AES256_SHA512,
   298  	},
   299  }
   300  
   301  // Test parameter selection for each curve, and that P224 fails automatic
   302  // parameter selection (see README for a discussion of P224). Ensures that
   303  // selecting a set of parameters automatically for the given curve works.
   304  func TestParamSelection(t *testing.T) {
   305  	for _, c := range testCases {
   306  		testParamSelection(t, c)
   307  	}
   308  }
   309  
   310  func testParamSelection(t *testing.T, c testCase) {
   311  	params := ParamsFromCurve(c.Curve)
   312  	if params == nil && c.Expected != nil {
   313  		t.Fatalf("%s (%s)\n", ErrInvalidParams.Error(), c.Name)
   314  	} else if params != nil && !cmpParams(params, c.Expected) {
   315  		t.Fatalf("ecies: parameters should be invalid (%s)\n", c.Name)
   316  	}
   317  
   318  	prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   319  	if err != nil {
   320  		t.Fatalf("%s (%s)\n", err.Error(), c.Name)
   321  	}
   322  
   323  	prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   324  	if err != nil {
   325  		t.Fatalf("%s (%s)\n", err.Error(), c.Name)
   326  	}
   327  
   328  	message := []byte("Hello, world.")
   329  	ct, err := Encrypt(rand.Reader, &prv2.PublicKey, message, nil, nil)
   330  	if err != nil {
   331  		t.Fatalf("%s (%s)\n", err.Error(), c.Name)
   332  	}
   333  
   334  	pt, err := prv2.Decrypt(ct, nil, nil)
   335  	if err != nil {
   336  		t.Fatalf("%s (%s)\n", err.Error(), c.Name)
   337  	}
   338  
   339  	if !bytes.Equal(pt, message) {
   340  		t.Fatalf("ecies: plaintext doesn't match message (%s)\n", c.Name)
   341  	}
   342  
   343  	_, err = prv1.Decrypt(ct, nil, nil)
   344  	if err == nil {
   345  		t.Fatalf("ecies: encryption should not have succeeded (%s)\n", c.Name)
   346  	}
   347  
   348  }
   349  
   350  // Ensure that the basic public key validation in the decryption operation
   351  // works.
   352  func TestBasicKeyValidation(t *testing.T) {
   353  	badBytes := []byte{0, 1, 5, 6, 7, 8, 9}
   354  
   355  	prv, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   356  	if err != nil {
   357  		t.Fatal(err)
   358  	}
   359  
   360  	message := []byte("Hello, world.")
   361  	ct, err := Encrypt(rand.Reader, &prv.PublicKey, message, nil, nil)
   362  	if err != nil {
   363  		t.Fatal(err)
   364  	}
   365  
   366  	for _, b := range badBytes {
   367  		ct[0] = b
   368  		_, err := prv.Decrypt(ct, nil, nil)
   369  		if err != ErrInvalidPublicKey {
   370  			t.Fatal("ecies: validated an invalid key")
   371  		}
   372  	}
   373  }
   374  
   375  func TestBox(t *testing.T) {
   376  	prv1 := hexKey("4b50fa71f5c3eeb8fdc452224b2395af2fcc3d125e06c32c82e048c0559db03f")
   377  	prv2 := hexKey("d0b043b4c5d657670778242d82d68a29d25d7d711127d17b8e299f156dad361a")
   378  	pub2 := &prv2.PublicKey
   379  
   380  	message := []byte("Hello, world.")
   381  	ct, err := Encrypt(rand.Reader, pub2, message, nil, nil)
   382  	if err != nil {
   383  		t.Fatal(err)
   384  	}
   385  
   386  	pt, err := prv2.Decrypt(ct, nil, nil)
   387  	if err != nil {
   388  		t.Fatal(err)
   389  	}
   390  	if !bytes.Equal(pt, message) {
   391  		t.Fatal("ecies: plaintext doesn't match message")
   392  	}
   393  	if _, err = prv1.Decrypt(ct, nil, nil); err == nil {
   394  		t.Fatal("ecies: encryption should not have succeeded")
   395  	}
   396  }
   397  
   398  // Verify GenerateShared against static values - useful when
   399  // debugging changes in underlying libs
   400  func TestSharedKeyStatic(t *testing.T) {
   401  	prv1 := hexKey("7ebbc6a8358bc76dd73ebc557056702c8cfc34e5cfcd90eb83af0347575fd2ad")
   402  	prv2 := hexKey("6a3d6396903245bba5837752b9e0348874e72db0c4e11e9c485a81b4ea4353b9")
   403  
   404  	skLen := MaxSharedKeyLength(&prv1.PublicKey) / 2
   405  
   406  	sk1, err := prv1.GenerateShared(&prv2.PublicKey, skLen, skLen)
   407  	if err != nil {
   408  		t.Fatal(err)
   409  	}
   410  
   411  	sk2, err := prv2.GenerateShared(&prv1.PublicKey, skLen, skLen)
   412  	if err != nil {
   413  		t.Fatal(err)
   414  	}
   415  
   416  	if !bytes.Equal(sk1, sk2) {
   417  		t.Fatal(ErrBadSharedKeys)
   418  	}
   419  
   420  	sk, _ := hex.DecodeString("167ccc13ac5e8a26b131c3446030c60fbfac6aa8e31149d0869f93626a4cdf62")
   421  	if !bytes.Equal(sk1, sk) {
   422  		t.Fatalf("shared secret mismatch: want: %x have: %x", sk, sk1)
   423  	}
   424  }
   425  
   426  func hexKey(prv string) *PrivateKey {
   427  	key, err := crypto.HexToECDSA(prv)
   428  	if err != nil {
   429  		panic(err)
   430  	}
   431  	return ImportECDSA(key)
   432  }