github.com/aquanetwork/aquachain@v1.7.8/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  	"gitlab.com/aquachain/aquachain/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  // Validate the ECDH component.
    81  func TestSharedKey(t *testing.T) {
    82  	prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil)
    83  	if err != nil {
    84  		fmt.Println(err.Error())
    85  		t.FailNow()
    86  	}
    87  	skLen := MaxSharedKeyLength(&prv1.PublicKey) / 2
    88  
    89  	prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil)
    90  	if err != nil {
    91  		fmt.Println(err.Error())
    92  		t.FailNow()
    93  	}
    94  
    95  	sk1, err := prv1.GenerateShared(&prv2.PublicKey, skLen, skLen)
    96  	if err != nil {
    97  		fmt.Println(err.Error())
    98  		t.FailNow()
    99  	}
   100  
   101  	sk2, err := prv2.GenerateShared(&prv1.PublicKey, skLen, skLen)
   102  	if err != nil {
   103  		fmt.Println(err.Error())
   104  		t.FailNow()
   105  	}
   106  
   107  	if !bytes.Equal(sk1, sk2) {
   108  		fmt.Println(ErrBadSharedKeys.Error())
   109  		t.FailNow()
   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  		fmt.Println(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  		fmt.Println(err.Error())
   157  		t.FailNow()
   158  	}
   159  
   160  	prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   161  	if err != nil {
   162  		fmt.Println(err.Error())
   163  		t.FailNow()
   164  	}
   165  
   166  	_, err = prv1.GenerateShared(&prv2.PublicKey, 32, 32)
   167  	if err != ErrSharedKeyTooBig {
   168  		fmt.Println("ecdh: shared key should be too large for curve")
   169  		t.FailNow()
   170  	}
   171  
   172  	_, err = prv2.GenerateShared(&prv1.PublicKey, 32, 32)
   173  	if err != ErrSharedKeyTooBig {
   174  		fmt.Println("ecdh: shared key should be too large for curve")
   175  		t.FailNow()
   176  	}
   177  }
   178  
   179  // Benchmark the generation of P256 keys.
   180  func BenchmarkGenerateKeyP256(b *testing.B) {
   181  	for i := 0; i < b.N; i++ {
   182  		if _, err := GenerateKey(rand.Reader, elliptic.P256(), nil); err != nil {
   183  			fmt.Println(err.Error())
   184  			b.FailNow()
   185  		}
   186  	}
   187  }
   188  
   189  // Benchmark the generation of P256 shared keys.
   190  func BenchmarkGenSharedKeyP256(b *testing.B) {
   191  	prv, err := GenerateKey(rand.Reader, elliptic.P256(), nil)
   192  	if err != nil {
   193  		fmt.Println(err.Error())
   194  		b.FailNow()
   195  	}
   196  	b.ResetTimer()
   197  	for i := 0; i < b.N; i++ {
   198  		_, err := prv.GenerateShared(&prv.PublicKey, 16, 16)
   199  		if err != nil {
   200  			fmt.Println(err.Error())
   201  			b.FailNow()
   202  		}
   203  	}
   204  }
   205  
   206  // Benchmark the generation of S256 shared keys.
   207  func BenchmarkGenSharedKeyS256(b *testing.B) {
   208  	prv, err := GenerateKey(rand.Reader, crypto.S256(), nil)
   209  	if err != nil {
   210  		fmt.Println(err.Error())
   211  		b.FailNow()
   212  	}
   213  	b.ResetTimer()
   214  	for i := 0; i < b.N; i++ {
   215  		_, err := prv.GenerateShared(&prv.PublicKey, 16, 16)
   216  		if err != nil {
   217  			fmt.Println(err.Error())
   218  			b.FailNow()
   219  		}
   220  	}
   221  }
   222  
   223  // Verify that an encrypted message can be successfully decrypted.
   224  func TestEncryptDecrypt(t *testing.T) {
   225  	prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   226  	if err != nil {
   227  		fmt.Println(err.Error())
   228  		t.FailNow()
   229  	}
   230  
   231  	prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   232  	if err != nil {
   233  		fmt.Println(err.Error())
   234  		t.FailNow()
   235  	}
   236  
   237  	message := []byte("Hello, world.")
   238  	ct, err := Encrypt(rand.Reader, &prv2.PublicKey, message, nil, nil)
   239  	if err != nil {
   240  		fmt.Println(err.Error())
   241  		t.FailNow()
   242  	}
   243  
   244  	pt, err := prv2.Decrypt(ct, nil, nil)
   245  	if err != nil {
   246  		fmt.Println(err.Error())
   247  		t.FailNow()
   248  	}
   249  
   250  	if !bytes.Equal(pt, message) {
   251  		fmt.Println("ecies: plaintext doesn't match message")
   252  		t.FailNow()
   253  	}
   254  
   255  	_, err = prv1.Decrypt(ct, nil, nil)
   256  	if err == nil {
   257  		fmt.Println("ecies: encryption should not have succeeded")
   258  		t.FailNow()
   259  	}
   260  }
   261  
   262  func TestDecryptShared2(t *testing.T) {
   263  	prv, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   264  	if err != nil {
   265  		t.Fatal(err)
   266  	}
   267  	message := []byte("Hello, world.")
   268  	shared2 := []byte("shared data 2")
   269  	ct, err := Encrypt(rand.Reader, &prv.PublicKey, message, nil, shared2)
   270  	if err != nil {
   271  		t.Fatal(err)
   272  	}
   273  
   274  	// Check that decrypting with correct shared data works.
   275  	pt, err := prv.Decrypt(ct, nil, shared2)
   276  	if err != nil {
   277  		t.Fatal(err)
   278  	}
   279  	if !bytes.Equal(pt, message) {
   280  		t.Fatal("ecies: plaintext doesn't match message")
   281  	}
   282  
   283  	// Decrypting without shared data or incorrect shared data fails.
   284  	if _, err = prv.Decrypt(ct, nil, nil); err == nil {
   285  		t.Fatal("ecies: decrypting without shared data didn't fail")
   286  	}
   287  	if _, err = prv.Decrypt(ct, nil, []byte("garbage")); err == nil {
   288  		t.Fatal("ecies: decrypting with incorrect shared data didn't fail")
   289  	}
   290  }
   291  
   292  type testCase struct {
   293  	Curve    elliptic.Curve
   294  	Name     string
   295  	Expected *ECIESParams
   296  }
   297  
   298  var testCases = []testCase{
   299  	{
   300  		Curve:    elliptic.P256(),
   301  		Name:     "P256",
   302  		Expected: ECIES_AES128_SHA256,
   303  	},
   304  	{
   305  		Curve:    elliptic.P384(),
   306  		Name:     "P384",
   307  		Expected: ECIES_AES256_SHA384,
   308  	},
   309  	{
   310  		Curve:    elliptic.P521(),
   311  		Name:     "P521",
   312  		Expected: ECIES_AES256_SHA512,
   313  	},
   314  }
   315  
   316  // Test parameter selection for each curve, and that P224 fails automatic
   317  // parameter selection (see README for a discussion of P224). Ensures that
   318  // selecting a set of parameters automatically for the given curve works.
   319  func TestParamSelection(t *testing.T) {
   320  	for _, c := range testCases {
   321  		testParamSelection(t, c)
   322  	}
   323  }
   324  
   325  func testParamSelection(t *testing.T, c testCase) {
   326  	params := ParamsFromCurve(c.Curve)
   327  	if params == nil && c.Expected != nil {
   328  		fmt.Printf("%s (%s)\n", ErrInvalidParams.Error(), c.Name)
   329  		t.FailNow()
   330  	} else if params != nil && !cmpParams(params, c.Expected) {
   331  		fmt.Printf("ecies: parameters should be invalid (%s)\n",
   332  			c.Name)
   333  		t.FailNow()
   334  	}
   335  
   336  	prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   337  	if err != nil {
   338  		fmt.Printf("%s (%s)\n", err.Error(), c.Name)
   339  		t.FailNow()
   340  	}
   341  
   342  	prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   343  	if err != nil {
   344  		fmt.Printf("%s (%s)\n", err.Error(), c.Name)
   345  		t.FailNow()
   346  	}
   347  
   348  	message := []byte("Hello, world.")
   349  	ct, err := Encrypt(rand.Reader, &prv2.PublicKey, message, nil, nil)
   350  	if err != nil {
   351  		fmt.Printf("%s (%s)\n", err.Error(), c.Name)
   352  		t.FailNow()
   353  	}
   354  
   355  	pt, err := prv2.Decrypt(ct, nil, nil)
   356  	if err != nil {
   357  		fmt.Printf("%s (%s)\n", err.Error(), c.Name)
   358  		t.FailNow()
   359  	}
   360  
   361  	if !bytes.Equal(pt, message) {
   362  		fmt.Printf("ecies: plaintext doesn't match message (%s)\n",
   363  			c.Name)
   364  		t.FailNow()
   365  	}
   366  
   367  	_, err = prv1.Decrypt(ct, nil, nil)
   368  	if err == nil {
   369  		fmt.Printf("ecies: encryption should not have succeeded (%s)\n",
   370  			c.Name)
   371  		t.FailNow()
   372  	}
   373  
   374  }
   375  
   376  // Ensure that the basic public key validation in the decryption operation
   377  // works.
   378  func TestBasicKeyValidation(t *testing.T) {
   379  	badBytes := []byte{0, 1, 5, 6, 7, 8, 9}
   380  
   381  	prv, err := GenerateKey(rand.Reader, DefaultCurve, nil)
   382  	if err != nil {
   383  		fmt.Println(err.Error())
   384  		t.FailNow()
   385  	}
   386  
   387  	message := []byte("Hello, world.")
   388  	ct, err := Encrypt(rand.Reader, &prv.PublicKey, message, nil, nil)
   389  	if err != nil {
   390  		fmt.Println(err.Error())
   391  		t.FailNow()
   392  	}
   393  
   394  	for _, b := range badBytes {
   395  		ct[0] = b
   396  		_, err := prv.Decrypt(ct, nil, nil)
   397  		if err != ErrInvalidPublicKey {
   398  			fmt.Println("ecies: validated an invalid key")
   399  			t.FailNow()
   400  		}
   401  	}
   402  }
   403  
   404  func TestBox(t *testing.T) {
   405  	prv1 := hexKey("4b50fa71f5c3eeb8fdc452224b2395af2fcc3d125e06c32c82e048c0559db03f")
   406  	prv2 := hexKey("d0b043b4c5d657670778242d82d68a29d25d7d711127d17b8e299f156dad361a")
   407  	pub2 := &prv2.PublicKey
   408  
   409  	message := []byte("Hello, world.")
   410  	ct, err := Encrypt(rand.Reader, pub2, message, nil, nil)
   411  	if err != nil {
   412  		t.Fatal(err)
   413  	}
   414  
   415  	pt, err := prv2.Decrypt(ct, nil, nil)
   416  	if err != nil {
   417  		t.Fatal(err)
   418  	}
   419  	if !bytes.Equal(pt, message) {
   420  		t.Fatal("ecies: plaintext doesn't match message")
   421  	}
   422  	if _, err = prv1.Decrypt(ct, nil, nil); err == nil {
   423  		t.Fatal("ecies: encryption should not have succeeded")
   424  	}
   425  }
   426  
   427  // Verify GenerateShared against static values - useful when
   428  // debugging changes in underlying libs
   429  func TestSharedKeyStatic(t *testing.T) {
   430  	prv1 := hexKey("7ebbc6a8358bc76dd73ebc557056702c8cfc34e5cfcd90eb83af0347575fd2ad")
   431  	prv2 := hexKey("6a3d6396903245bba5837752b9e0348874e72db0c4e11e9c485a81b4ea4353b9")
   432  
   433  	skLen := MaxSharedKeyLength(&prv1.PublicKey) / 2
   434  
   435  	sk1, err := prv1.GenerateShared(&prv2.PublicKey, skLen, skLen)
   436  	if err != nil {
   437  		fmt.Println(err.Error())
   438  		t.FailNow()
   439  	}
   440  
   441  	sk2, err := prv2.GenerateShared(&prv1.PublicKey, skLen, skLen)
   442  	if err != nil {
   443  		fmt.Println(err.Error())
   444  		t.FailNow()
   445  	}
   446  
   447  	if !bytes.Equal(sk1, sk2) {
   448  		fmt.Println(ErrBadSharedKeys.Error())
   449  		t.FailNow()
   450  	}
   451  
   452  	sk, _ := hex.DecodeString("167ccc13ac5e8a26b131c3446030c60fbfac6aa8e31149d0869f93626a4cdf62")
   453  	if !bytes.Equal(sk1, sk) {
   454  		t.Fatalf("shared secret mismatch: want: %x have: %x", sk, sk1)
   455  	}
   456  }
   457  
   458  func hexKey(prv string) *PrivateKey {
   459  	key, err := crypto.HexToECDSA(prv)
   460  	if err != nil {
   461  		panic(err)
   462  	}
   463  	return ImportECDSA(key)
   464  }