github.com/luckypickle/go-ethereum-vet@v1.14.2/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/luckypickle/go-ethereum-vet/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  		fmt.Println(err.Error())
    53  		t.FailNow()
    54  	}
    55  	if len(k) != 64 {
    56  		fmt.Printf("KDF: generated key is the wrong size (%d instead of 64\n", len(k))
    57  		t.FailNow()
    58  	}
    59  }
    60  
    61  var ErrBadSharedKeys = fmt.Errorf("ecies: shared keys don't match")
    62  
    63  // cmpParams compares a set of ECIES parameters. We assume, as per the
    64  // docs, that AES is the only supported symmetric encryption algorithm.
    65  func cmpParams(p1, p2 *ECIESParams) bool {
    66  	return p1.hashAlgo == p2.hashAlgo &&
    67  		p1.KeyLen == p2.KeyLen &&
    68  		p1.BlockSize == p2.BlockSize
    69  }
    70  
    71  // cmpPublic returns true if the two public keys represent the same pojnt.
    72  func cmpPublic(pub1, pub2 PublicKey) bool {
    73  	if pub1.X == nil || pub1.Y == nil {
    74  		fmt.Println(ErrInvalidPublicKey.Error())
    75  		return false
    76  	}
    77  	if pub2.X == nil || pub2.Y == nil {
    78  		fmt.Println(ErrInvalidPublicKey.Error())
    79  		return false
    80  	}
    81  	pub1Out := elliptic.Marshal(pub1.Curve, pub1.X, pub1.Y)
    82  	pub2Out := elliptic.Marshal(pub2.Curve, pub2.X, pub2.Y)
    83  
    84  	return bytes.Equal(pub1Out, pub2Out)
    85  }
    86  
    87  // cmpPrivate returns true if the two private keys are the same.
    88  func cmpPrivate(prv1, prv2 *PrivateKey) bool {
    89  	if prv1 == nil || prv1.D == nil {
    90  		return false
    91  	} else if prv2 == nil || prv2.D == nil {
    92  		return false
    93  	} else if prv1.D.Cmp(prv2.D) != 0 {
    94  		return false
    95  	} else {
    96  		return cmpPublic(prv1.PublicKey, prv2.PublicKey)
    97  	}
    98  }
    99  
   100  // Validate the ECDH component.
   101  func TestSharedKey(t *testing.T) {
   102  	prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   103  	if err != nil {
   104  		fmt.Println(err.Error())
   105  		t.FailNow()
   106  	}
   107  	skLen := MaxSharedKeyLength(&prv1.PublicKey) / 2
   108  
   109  	prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   110  	if err != nil {
   111  		fmt.Println(err.Error())
   112  		t.FailNow()
   113  	}
   114  
   115  	sk1, err := prv1.GenerateShared(&prv2.PublicKey, skLen, skLen)
   116  	if err != nil {
   117  		fmt.Println(err.Error())
   118  		t.FailNow()
   119  	}
   120  
   121  	sk2, err := prv2.GenerateShared(&prv1.PublicKey, skLen, skLen)
   122  	if err != nil {
   123  		fmt.Println(err.Error())
   124  		t.FailNow()
   125  	}
   126  
   127  	if !bytes.Equal(sk1, sk2) {
   128  		fmt.Println(ErrBadSharedKeys.Error())
   129  		t.FailNow()
   130  	}
   131  }
   132  
   133  func TestSharedKeyPadding(t *testing.T) {
   134  	// sanity checks
   135  	prv0 := hexKey("1adf5c18167d96a1f9a0b1ef63be8aa27eaf6032c233b2b38f7850cf5b859fd9")
   136  	prv1 := hexKey("0097a076fc7fcd9208240668e31c9abee952cbb6e375d1b8febc7499d6e16f1a")
   137  	x0, _ := new(big.Int).SetString("1a8ed022ff7aec59dc1b440446bdda5ff6bcb3509a8b109077282b361efffbd8", 16)
   138  	x1, _ := new(big.Int).SetString("6ab3ac374251f638d0abb3ef596d1dc67955b507c104e5f2009724812dc027b8", 16)
   139  	y0, _ := new(big.Int).SetString("e040bd480b1deccc3bc40bd5b1fdcb7bfd352500b477cb9471366dbd4493f923", 16)
   140  	y1, _ := new(big.Int).SetString("8ad915f2b503a8be6facab6588731fefeb584fd2dfa9a77a5e0bba1ec439e4fa", 16)
   141  
   142  	if prv0.PublicKey.X.Cmp(x0) != 0 {
   143  		t.Errorf("mismatched prv0.X:\nhave: %x\nwant: %x\n", prv0.PublicKey.X.Bytes(), x0.Bytes())
   144  	}
   145  	if prv0.PublicKey.Y.Cmp(y0) != 0 {
   146  		t.Errorf("mismatched prv0.Y:\nhave: %x\nwant: %x\n", prv0.PublicKey.Y.Bytes(), y0.Bytes())
   147  	}
   148  	if prv1.PublicKey.X.Cmp(x1) != 0 {
   149  		t.Errorf("mismatched prv1.X:\nhave: %x\nwant: %x\n", prv1.PublicKey.X.Bytes(), x1.Bytes())
   150  	}
   151  	if prv1.PublicKey.Y.Cmp(y1) != 0 {
   152  		t.Errorf("mismatched prv1.Y:\nhave: %x\nwant: %x\n", prv1.PublicKey.Y.Bytes(), y1.Bytes())
   153  	}
   154  
   155  	// test shared secret generation
   156  	sk1, err := prv0.GenerateShared(&prv1.PublicKey, 16, 16)
   157  	if err != nil {
   158  		fmt.Println(err.Error())
   159  	}
   160  
   161  	sk2, err := prv1.GenerateShared(&prv0.PublicKey, 16, 16)
   162  	if err != nil {
   163  		t.Fatal(err.Error())
   164  	}
   165  
   166  	if !bytes.Equal(sk1, sk2) {
   167  		t.Fatal(ErrBadSharedKeys.Error())
   168  	}
   169  }
   170  
   171  // Verify that the key generation code fails when too much key data is
   172  // requested.
   173  func TestTooBigSharedKey(t *testing.T) {
   174  	prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   175  	if err != nil {
   176  		fmt.Println(err.Error())
   177  		t.FailNow()
   178  	}
   179  
   180  	prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   181  	if err != nil {
   182  		fmt.Println(err.Error())
   183  		t.FailNow()
   184  	}
   185  
   186  	_, err = prv1.GenerateShared(&prv2.PublicKey, 32, 32)
   187  	if err != ErrSharedKeyTooBig {
   188  		fmt.Println("ecdh: shared key should be too large for curve")
   189  		t.FailNow()
   190  	}
   191  
   192  	_, err = prv2.GenerateShared(&prv1.PublicKey, 32, 32)
   193  	if err != ErrSharedKeyTooBig {
   194  		fmt.Println("ecdh: shared key should be too large for curve")
   195  		t.FailNow()
   196  	}
   197  }
   198  
   199  // Benchmark the generation of P256 keys.
   200  func BenchmarkGenerateKeyP256(b *testing.B) {
   201  	for i := 0; i < b.N; i++ {
   202  		if _, err := GenerateKey(rand.Reader, elliptic.P256(), nil); err != nil {
   203  			fmt.Println(err.Error())
   204  			b.FailNow()
   205  		}
   206  	}
   207  }
   208  
   209  // Benchmark the generation of P256 shared keys.
   210  func BenchmarkGenSharedKeyP256(b *testing.B) {
   211  	prv, err := GenerateKey(rand.Reader, elliptic.P256(), nil)
   212  	if err != nil {
   213  		fmt.Println(err.Error())
   214  		b.FailNow()
   215  	}
   216  	b.ResetTimer()
   217  	for i := 0; i < b.N; i++ {
   218  		_, err := prv.GenerateShared(&prv.PublicKey, 16, 16)
   219  		if err != nil {
   220  			fmt.Println(err.Error())
   221  			b.FailNow()
   222  		}
   223  	}
   224  }
   225  
   226  // Benchmark the generation of S256 shared keys.
   227  func BenchmarkGenSharedKeyS256(b *testing.B) {
   228  	prv, err := GenerateKey(rand.Reader, crypto.S256(), nil)
   229  	if err != nil {
   230  		fmt.Println(err.Error())
   231  		b.FailNow()
   232  	}
   233  	b.ResetTimer()
   234  	for i := 0; i < b.N; i++ {
   235  		_, err := prv.GenerateShared(&prv.PublicKey, 16, 16)
   236  		if err != nil {
   237  			fmt.Println(err.Error())
   238  			b.FailNow()
   239  		}
   240  	}
   241  }
   242  
   243  // Verify that an encrypted message can be successfully decrypted.
   244  func TestEncryptDecrypt(t *testing.T) {
   245  	prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   246  	if err != nil {
   247  		fmt.Println(err.Error())
   248  		t.FailNow()
   249  	}
   250  
   251  	prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   252  	if err != nil {
   253  		fmt.Println(err.Error())
   254  		t.FailNow()
   255  	}
   256  
   257  	message := []byte("Hello, world.")
   258  	ct, err := Encrypt(rand.Reader, &prv2.PublicKey, message, nil, nil)
   259  	if err != nil {
   260  		fmt.Println(err.Error())
   261  		t.FailNow()
   262  	}
   263  
   264  	pt, err := prv2.Decrypt(ct, nil, nil)
   265  	if err != nil {
   266  		fmt.Println(err.Error())
   267  		t.FailNow()
   268  	}
   269  
   270  	if !bytes.Equal(pt, message) {
   271  		fmt.Println("ecies: plaintext doesn't match message")
   272  		t.FailNow()
   273  	}
   274  
   275  	_, err = prv1.Decrypt(ct, nil, nil)
   276  	if err == nil {
   277  		fmt.Println("ecies: encryption should not have succeeded")
   278  		t.FailNow()
   279  	}
   280  }
   281  
   282  func TestDecryptShared2(t *testing.T) {
   283  	prv, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   284  	if err != nil {
   285  		t.Fatal(err)
   286  	}
   287  	message := []byte("Hello, world.")
   288  	shared2 := []byte("shared data 2")
   289  	ct, err := Encrypt(rand.Reader, &prv.PublicKey, message, nil, shared2)
   290  	if err != nil {
   291  		t.Fatal(err)
   292  	}
   293  
   294  	// Check that decrypting with correct shared data works.
   295  	pt, err := prv.Decrypt(ct, nil, shared2)
   296  	if err != nil {
   297  		t.Fatal(err)
   298  	}
   299  	if !bytes.Equal(pt, message) {
   300  		t.Fatal("ecies: plaintext doesn't match message")
   301  	}
   302  
   303  	// Decrypting without shared data or incorrect shared data fails.
   304  	if _, err = prv.Decrypt(ct, nil, nil); err == nil {
   305  		t.Fatal("ecies: decrypting without shared data didn't fail")
   306  	}
   307  	if _, err = prv.Decrypt(ct, nil, []byte("garbage")); err == nil {
   308  		t.Fatal("ecies: decrypting with incorrect shared data didn't fail")
   309  	}
   310  }
   311  
   312  type testCase struct {
   313  	Curve    elliptic.Curve
   314  	Name     string
   315  	Expected *ECIESParams
   316  }
   317  
   318  var testCases = []testCase{
   319  	{
   320  		Curve:    elliptic.P256(),
   321  		Name:     "P256",
   322  		Expected: ECIES_AES128_SHA256,
   323  	},
   324  	{
   325  		Curve:    elliptic.P384(),
   326  		Name:     "P384",
   327  		Expected: ECIES_AES256_SHA384,
   328  	},
   329  	{
   330  		Curve:    elliptic.P521(),
   331  		Name:     "P521",
   332  		Expected: ECIES_AES256_SHA512,
   333  	},
   334  }
   335  
   336  // Test parameter selection for each curve, and that P224 fails automatic
   337  // parameter selection (see README for a discussion of P224). Ensures that
   338  // selecting a set of parameters automatically for the given curve works.
   339  func TestParamSelection(t *testing.T) {
   340  	for _, c := range testCases {
   341  		testParamSelection(t, c)
   342  	}
   343  }
   344  
   345  func testParamSelection(t *testing.T, c testCase) {
   346  	params := ParamsFromCurve(c.Curve)
   347  	if params == nil && c.Expected != nil {
   348  		fmt.Printf("%s (%s)\n", ErrInvalidParams.Error(), c.Name)
   349  		t.FailNow()
   350  	} else if params != nil && !cmpParams(params, c.Expected) {
   351  		fmt.Printf("ecies: parameters should be invalid (%s)\n",
   352  			c.Name)
   353  		t.FailNow()
   354  	}
   355  
   356  	prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   357  	if err != nil {
   358  		fmt.Printf("%s (%s)\n", err.Error(), c.Name)
   359  		t.FailNow()
   360  	}
   361  
   362  	prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   363  	if err != nil {
   364  		fmt.Printf("%s (%s)\n", err.Error(), c.Name)
   365  		t.FailNow()
   366  	}
   367  
   368  	message := []byte("Hello, world.")
   369  	ct, err := Encrypt(rand.Reader, &prv2.PublicKey, message, nil, nil)
   370  	if err != nil {
   371  		fmt.Printf("%s (%s)\n", err.Error(), c.Name)
   372  		t.FailNow()
   373  	}
   374  
   375  	pt, err := prv2.Decrypt(ct, nil, nil)
   376  	if err != nil {
   377  		fmt.Printf("%s (%s)\n", err.Error(), c.Name)
   378  		t.FailNow()
   379  	}
   380  
   381  	if !bytes.Equal(pt, message) {
   382  		fmt.Printf("ecies: plaintext doesn't match message (%s)\n",
   383  			c.Name)
   384  		t.FailNow()
   385  	}
   386  
   387  	_, err = prv1.Decrypt(ct, nil, nil)
   388  	if err == nil {
   389  		fmt.Printf("ecies: encryption should not have succeeded (%s)\n",
   390  			c.Name)
   391  		t.FailNow()
   392  	}
   393  
   394  }
   395  
   396  // Ensure that the basic public key validation in the decryption operation
   397  // works.
   398  func TestBasicKeyValidation(t *testing.T) {
   399  	badBytes := []byte{0, 1, 5, 6, 7, 8, 9}
   400  
   401  	prv, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   402  	if err != nil {
   403  		fmt.Println(err.Error())
   404  		t.FailNow()
   405  	}
   406  
   407  	message := []byte("Hello, world.")
   408  	ct, err := Encrypt(rand.Reader, &prv.PublicKey, message, nil, nil)
   409  	if err != nil {
   410  		fmt.Println(err.Error())
   411  		t.FailNow()
   412  	}
   413  
   414  	for _, b := range badBytes {
   415  		ct[0] = b
   416  		_, err := prv.Decrypt(ct, nil, nil)
   417  		if err != ErrInvalidPublicKey {
   418  			fmt.Println("ecies: validated an invalid key")
   419  			t.FailNow()
   420  		}
   421  	}
   422  }
   423  
   424  func TestBox(t *testing.T) {
   425  	prv1 := hexKey("4b50fa71f5c3eeb8fdc452224b2395af2fcc3d125e06c32c82e048c0559db03f")
   426  	prv2 := hexKey("d0b043b4c5d657670778242d82d68a29d25d7d711127d17b8e299f156dad361a")
   427  	pub2 := &prv2.PublicKey
   428  
   429  	message := []byte("Hello, world.")
   430  	ct, err := Encrypt(rand.Reader, pub2, message, nil, nil)
   431  	if err != nil {
   432  		t.Fatal(err)
   433  	}
   434  
   435  	pt, err := prv2.Decrypt(ct, nil, nil)
   436  	if err != nil {
   437  		t.Fatal(err)
   438  	}
   439  	if !bytes.Equal(pt, message) {
   440  		t.Fatal("ecies: plaintext doesn't match message")
   441  	}
   442  	if _, err = prv1.Decrypt(ct, nil, nil); err == nil {
   443  		t.Fatal("ecies: encryption should not have succeeded")
   444  	}
   445  }
   446  
   447  // Verify GenerateShared against static values - useful when
   448  // debugging changes in underlying libs
   449  func TestSharedKeyStatic(t *testing.T) {
   450  	prv1 := hexKey("7ebbc6a8358bc76dd73ebc557056702c8cfc34e5cfcd90eb83af0347575fd2ad")
   451  	prv2 := hexKey("6a3d6396903245bba5837752b9e0348874e72db0c4e11e9c485a81b4ea4353b9")
   452  
   453  	skLen := MaxSharedKeyLength(&prv1.PublicKey) / 2
   454  
   455  	sk1, err := prv1.GenerateShared(&prv2.PublicKey, skLen, skLen)
   456  	if err != nil {
   457  		fmt.Println(err.Error())
   458  		t.FailNow()
   459  	}
   460  
   461  	sk2, err := prv2.GenerateShared(&prv1.PublicKey, skLen, skLen)
   462  	if err != nil {
   463  		fmt.Println(err.Error())
   464  		t.FailNow()
   465  	}
   466  
   467  	if !bytes.Equal(sk1, sk2) {
   468  		fmt.Println(ErrBadSharedKeys.Error())
   469  		t.FailNow()
   470  	}
   471  
   472  	sk, _ := hex.DecodeString("167ccc13ac5e8a26b131c3446030c60fbfac6aa8e31149d0869f93626a4cdf62")
   473  	if !bytes.Equal(sk1, sk) {
   474  		t.Fatalf("shared secret mismatch: want: %x have: %x", sk, sk1)
   475  	}
   476  }
   477  
   478  func hexKey(prv string) *PrivateKey {
   479  	key, err := crypto.HexToECDSA(prv)
   480  	if err != nil {
   481  		panic(err)
   482  	}
   483  	return ImportECDSA(key)
   484  }