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