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