github.com/klaytn/klaytn@v1.12.1/crypto/ecies/ecies_test.go (about) 1 // Copyright (c) 2018 The klaytn Authors. 2 // Copyright (c) 2013 Kyle Isom <kyle@tyrfingr.is> 3 // Copyright (c) 2012 The Go Authors. All rights reserved. 4 // 5 // Redistribution and use in source and binary forms, with or without 6 // modification, are permitted provided that the following conditions are 7 // met: 8 // 9 // * Redistributions of source code must retain the above copyright 10 // notice, this list of conditions and the following disclaimer. 11 // * Redistributions in binary form must reproduce the above 12 // copyright notice, this list of conditions and the following disclaimer 13 // in the documentation and/or other materials provided with the 14 // distribution. 15 // * Neither the name of Google Inc. nor the names of its 16 // contributors may be used to endorse or promote products derived from 17 // this software without specific prior written permission. 18 // 19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 // 31 // This file is derived from crypto/ecies/ecies_test.go (2018/06/04). 32 // Modified and improved for the klaytn development. 33 34 package ecies 35 36 import ( 37 "bytes" 38 "crypto/elliptic" 39 "crypto/rand" 40 "crypto/sha256" 41 "encoding/hex" 42 "fmt" 43 "math/big" 44 "testing" 45 46 "github.com/klaytn/klaytn/crypto" 47 ) 48 49 // Ensure the KDF generates appropriately sized keys. 50 func TestKDF(t *testing.T) { 51 msg := []byte("Hello, world") 52 h := sha256.New() 53 54 k, err := concatKDF(h, msg, nil, 64) 55 if err != nil { 56 t.Fatal(err) 57 } 58 if len(k) != 64 { 59 t.Fatalf("KDF: generated key is the wrong size (%d instead of 64\n", len(k)) 60 } 61 } 62 63 var ErrBadSharedKeys = fmt.Errorf("ecies: shared keys don't match") 64 65 // cmpParams compares a set of ECIES parameters. We assume, as per the 66 // docs, that AES is the only supported symmetric encryption algorithm. 67 func cmpParams(p1, p2 *ECIESParams) bool { 68 return p1.hashAlgo == p2.hashAlgo && 69 p1.KeyLen == p2.KeyLen && 70 p1.BlockSize == p2.BlockSize 71 } 72 73 // cmpPublic returns true if the two public keys represent the same pojnt. 74 func cmpPublic(pub1, pub2 PublicKey) bool { 75 if pub1.X == nil || pub1.Y == nil { 76 fmt.Println(ErrInvalidPublicKey.Error()) 77 return false 78 } 79 if pub2.X == nil || pub2.Y == nil { 80 fmt.Println(ErrInvalidPublicKey.Error()) 81 return false 82 } 83 pub1Out := elliptic.Marshal(pub1.Curve, pub1.X, pub1.Y) 84 pub2Out := elliptic.Marshal(pub2.Curve, pub2.X, pub2.Y) 85 86 return bytes.Equal(pub1Out, pub2Out) 87 } 88 89 // cmpPrivate returns true if the two private keys are the same. 90 func cmpPrivate(prv1, prv2 *PrivateKey) bool { 91 if prv1 == nil || prv1.D == nil { 92 return false 93 } else if prv2 == nil || prv2.D == nil { 94 return false 95 } else if prv1.D.Cmp(prv2.D) != 0 { 96 return false 97 } else { 98 return cmpPublic(prv1.PublicKey, prv2.PublicKey) 99 } 100 } 101 102 // Validate the ECDH component. 103 func TestSharedKey(t *testing.T) { 104 prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil) 105 if err != nil { 106 t.Fatal(err) 107 } 108 skLen := MaxSharedKeyLength(&prv1.PublicKey) / 2 109 110 prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil) 111 if err != nil { 112 t.Fatal(err) 113 } 114 115 sk1, err := prv1.GenerateShared(&prv2.PublicKey, skLen, skLen) 116 if err != nil { 117 t.Fatal(err) 118 } 119 120 sk2, err := prv2.GenerateShared(&prv1.PublicKey, skLen, skLen) 121 if err != nil { 122 t.Fatal(err) 123 } 124 125 if !bytes.Equal(sk1, sk2) { 126 t.Fatal(ErrBadSharedKeys) 127 } 128 } 129 130 func TestSharedKeyPadding(t *testing.T) { 131 // sanity checks 132 prv0 := hexKey("1adf5c18167d96a1f9a0b1ef63be8aa27eaf6032c233b2b38f7850cf5b859fd9") 133 prv1 := hexKey("0097a076fc7fcd9208240668e31c9abee952cbb6e375d1b8febc7499d6e16f1a") 134 x0, _ := new(big.Int).SetString("1a8ed022ff7aec59dc1b440446bdda5ff6bcb3509a8b109077282b361efffbd8", 16) 135 x1, _ := new(big.Int).SetString("6ab3ac374251f638d0abb3ef596d1dc67955b507c104e5f2009724812dc027b8", 16) 136 y0, _ := new(big.Int).SetString("e040bd480b1deccc3bc40bd5b1fdcb7bfd352500b477cb9471366dbd4493f923", 16) 137 y1, _ := new(big.Int).SetString("8ad915f2b503a8be6facab6588731fefeb584fd2dfa9a77a5e0bba1ec439e4fa", 16) 138 139 if prv0.PublicKey.X.Cmp(x0) != 0 { 140 t.Errorf("mismatched prv0.X:\nhave: %x\nwant: %x\n", prv0.PublicKey.X.Bytes(), x0.Bytes()) 141 } 142 if prv0.PublicKey.Y.Cmp(y0) != 0 { 143 t.Errorf("mismatched prv0.Y:\nhave: %x\nwant: %x\n", prv0.PublicKey.Y.Bytes(), y0.Bytes()) 144 } 145 if prv1.PublicKey.X.Cmp(x1) != 0 { 146 t.Errorf("mismatched prv1.X:\nhave: %x\nwant: %x\n", prv1.PublicKey.X.Bytes(), x1.Bytes()) 147 } 148 if prv1.PublicKey.Y.Cmp(y1) != 0 { 149 t.Errorf("mismatched prv1.Y:\nhave: %x\nwant: %x\n", prv1.PublicKey.Y.Bytes(), y1.Bytes()) 150 } 151 152 // test shared secret generation 153 sk1, err := prv0.GenerateShared(&prv1.PublicKey, 16, 16) 154 if err != nil { 155 fmt.Println(err.Error()) 156 } 157 158 sk2, err := prv1.GenerateShared(&prv0.PublicKey, 16, 16) 159 if err != nil { 160 t.Fatal(err.Error()) 161 } 162 163 if !bytes.Equal(sk1, sk2) { 164 t.Fatal(ErrBadSharedKeys.Error()) 165 } 166 } 167 168 // Verify that the key generation code fails when too much key data is 169 // requested. 170 func TestTooBigSharedKey(t *testing.T) { 171 prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil) 172 if err != nil { 173 t.Fatal(err) 174 } 175 176 prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil) 177 if err != nil { 178 t.Fatal(err) 179 } 180 181 _, err = prv1.GenerateShared(&prv2.PublicKey, 32, 32) 182 if err != ErrSharedKeyTooBig { 183 t.Fatal("ecdh: shared key should be too large for curve") 184 } 185 186 _, err = prv2.GenerateShared(&prv1.PublicKey, 32, 32) 187 if err != ErrSharedKeyTooBig { 188 t.Fatal("ecdh: shared key should be too large for curve") 189 } 190 } 191 192 // Benchmark the generation of P256 keys. 193 func BenchmarkGenerateKeyP256(b *testing.B) { 194 for i := 0; i < b.N; i++ { 195 if _, err := GenerateKey(rand.Reader, elliptic.P256(), nil); err != nil { 196 b.Fatal(err) 197 } 198 } 199 } 200 201 // Benchmark the generation of P256 shared keys. 202 func BenchmarkGenSharedKeyP256(b *testing.B) { 203 prv, err := GenerateKey(rand.Reader, elliptic.P256(), nil) 204 if err != nil { 205 b.Fatal(err) 206 } 207 b.ResetTimer() 208 for i := 0; i < b.N; i++ { 209 _, err := prv.GenerateShared(&prv.PublicKey, 16, 16) 210 if err != nil { 211 b.Fatal(err) 212 } 213 } 214 } 215 216 // Benchmark the generation of S256 shared keys. 217 func BenchmarkGenSharedKeyS256(b *testing.B) { 218 prv, err := GenerateKey(rand.Reader, crypto.S256(), nil) 219 if err != nil { 220 b.Fatal(err) 221 } 222 b.ResetTimer() 223 for i := 0; i < b.N; i++ { 224 _, err := prv.GenerateShared(&prv.PublicKey, 16, 16) 225 if err != nil { 226 b.Fatal(err) 227 } 228 } 229 } 230 231 // Verify that an encrypted message can be successfully decrypted. 232 func TestEncryptDecrypt(t *testing.T) { 233 prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil) 234 if err != nil { 235 t.Fatal(err) 236 } 237 238 prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil) 239 if err != nil { 240 t.Fatal(err) 241 } 242 243 message := []byte("Hello, world.") 244 ct, err := Encrypt(rand.Reader, &prv2.PublicKey, message, nil, nil) 245 if err != nil { 246 t.Fatal(err) 247 } 248 249 pt, err := prv2.Decrypt(ct, nil, nil) 250 if err != nil { 251 t.Fatal(err) 252 } 253 254 if !bytes.Equal(pt, message) { 255 t.Fatal("ecies: plaintext doesn't match message") 256 } 257 258 _, err = prv1.Decrypt(ct, nil, nil) 259 if err == nil { 260 t.Fatal("ecies: encryption should not have succeeded") 261 } 262 } 263 264 func TestDecryptShared2(t *testing.T) { 265 prv, err := GenerateKey(rand.Reader, DefaultCurve, nil) 266 if err != nil { 267 t.Fatal(err) 268 } 269 message := []byte("Hello, world.") 270 shared2 := []byte("shared data 2") 271 ct, err := Encrypt(rand.Reader, &prv.PublicKey, message, nil, shared2) 272 if err != nil { 273 t.Fatal(err) 274 } 275 276 // Check that decrypting with correct shared data works. 277 pt, err := prv.Decrypt(ct, nil, shared2) 278 if err != nil { 279 t.Fatal(err) 280 } 281 if !bytes.Equal(pt, message) { 282 t.Fatal("ecies: plaintext doesn't match message") 283 } 284 285 // Decrypting without shared data or incorrect shared data fails. 286 if _, err = prv.Decrypt(ct, nil, nil); err == nil { 287 t.Fatal("ecies: decrypting without shared data didn't fail") 288 } 289 if _, err = prv.Decrypt(ct, nil, []byte("garbage")); err == nil { 290 t.Fatal("ecies: decrypting with incorrect shared data didn't fail") 291 } 292 } 293 294 type testCase struct { 295 Curve elliptic.Curve 296 Name string 297 Expected *ECIESParams 298 } 299 300 var testCases = []testCase{ 301 { 302 Curve: elliptic.P256(), 303 Name: "P256", 304 Expected: ECIES_AES128_SHA256, 305 }, 306 { 307 Curve: elliptic.P384(), 308 Name: "P384", 309 Expected: ECIES_AES256_SHA384, 310 }, 311 { 312 Curve: elliptic.P521(), 313 Name: "P521", 314 Expected: ECIES_AES256_SHA512, 315 }, 316 } 317 318 // Test parameter selection for each curve, and that P224 fails automatic 319 // parameter selection (see README for a discussion of P224). Ensures that 320 // selecting a set of parameters automatically for the given curve works. 321 func TestParamSelection(t *testing.T) { 322 for _, c := range testCases { 323 testParamSelection(t, c) 324 } 325 } 326 327 func testParamSelection(t *testing.T, c testCase) { 328 params := ParamsFromCurve(c.Curve) 329 if params == nil && c.Expected != nil { 330 t.Fatalf("%s (%s)\n", ErrInvalidParams.Error(), c.Name) 331 } else if params != nil && !cmpParams(params, c.Expected) { 332 t.Fatalf("ecies: parameters should be invalid (%s)\n", c.Name) 333 } 334 335 prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil) 336 if err != nil { 337 t.Fatalf("%s (%s)\n", err.Error(), c.Name) 338 } 339 340 prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil) 341 if err != nil { 342 t.Fatalf("%s (%s)\n", err.Error(), c.Name) 343 } 344 345 message := []byte("Hello, world.") 346 ct, err := Encrypt(rand.Reader, &prv2.PublicKey, message, nil, nil) 347 if err != nil { 348 t.Fatalf("%s (%s)\n", err.Error(), c.Name) 349 } 350 351 pt, err := prv2.Decrypt(ct, nil, nil) 352 if err != nil { 353 t.Fatalf("%s (%s)\n", err.Error(), c.Name) 354 } 355 356 if !bytes.Equal(pt, message) { 357 t.Fatalf("ecies: plaintext doesn't match message (%s)\n", c.Name) 358 } 359 360 _, err = prv1.Decrypt(ct, nil, nil) 361 if err == nil { 362 t.Fatalf("ecies: encryption should not have succeeded (%s)\n", c.Name) 363 } 364 } 365 366 // Ensure that the basic public key validation in the decryption operation 367 // works. 368 func TestBasicKeyValidation(t *testing.T) { 369 badBytes := []byte{0, 1, 5, 6, 7, 8, 9} 370 371 prv, err := GenerateKey(rand.Reader, DefaultCurve, nil) 372 if err != nil { 373 t.Fatal(err) 374 } 375 376 message := []byte("Hello, world.") 377 ct, err := Encrypt(rand.Reader, &prv.PublicKey, message, nil, nil) 378 if err != nil { 379 t.Fatal(err) 380 } 381 382 for _, b := range badBytes { 383 ct[0] = b 384 _, err := prv.Decrypt(ct, nil, nil) 385 if err != ErrInvalidPublicKey { 386 t.Fatal("ecies: validated an invalid key") 387 } 388 } 389 } 390 391 func TestBox(t *testing.T) { 392 prv1 := hexKey("4b50fa71f5c3eeb8fdc452224b2395af2fcc3d125e06c32c82e048c0559db03f") 393 prv2 := hexKey("d0b043b4c5d657670778242d82d68a29d25d7d711127d17b8e299f156dad361a") 394 pub2 := &prv2.PublicKey 395 396 message := []byte("Hello, world.") 397 ct, err := Encrypt(rand.Reader, pub2, message, nil, nil) 398 if err != nil { 399 t.Fatal(err) 400 } 401 402 pt, err := prv2.Decrypt(ct, nil, nil) 403 if err != nil { 404 t.Fatal(err) 405 } 406 if !bytes.Equal(pt, message) { 407 t.Fatal("ecies: plaintext doesn't match message") 408 } 409 if _, err = prv1.Decrypt(ct, nil, nil); err == nil { 410 t.Fatal("ecies: encryption should not have succeeded") 411 } 412 } 413 414 // Verify GenerateShared against static values - useful when 415 // debugging changes in underlying libs 416 func TestSharedKeyStatic(t *testing.T) { 417 prv1 := hexKey("7ebbc6a8358bc76dd73ebc557056702c8cfc34e5cfcd90eb83af0347575fd2ad") 418 prv2 := hexKey("6a3d6396903245bba5837752b9e0348874e72db0c4e11e9c485a81b4ea4353b9") 419 420 skLen := MaxSharedKeyLength(&prv1.PublicKey) / 2 421 422 sk1, err := prv1.GenerateShared(&prv2.PublicKey, skLen, skLen) 423 if err != nil { 424 t.Fatal(err) 425 } 426 427 sk2, err := prv2.GenerateShared(&prv1.PublicKey, skLen, skLen) 428 if err != nil { 429 t.Fatal(err) 430 } 431 432 if !bytes.Equal(sk1, sk2) { 433 t.Fatal(ErrBadSharedKeys) 434 } 435 436 sk, _ := hex.DecodeString("167ccc13ac5e8a26b131c3446030c60fbfac6aa8e31149d0869f93626a4cdf62") 437 if !bytes.Equal(sk1, sk) { 438 t.Fatalf("shared secret mismatch: want: %x have: %x", sk, sk1) 439 } 440 } 441 442 func hexKey(prv string) *PrivateKey { 443 key, err := crypto.HexToECDSA(prv) 444 if err != nil { 445 panic(err) 446 } 447 return ImportECDSA(key) 448 }