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