github.com/ethersphere/bee/v2@v2.2.0/pkg/crypto/dh_test.go (about) 1 // Copyright 2020 The Swarm Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package crypto_test 6 7 import ( 8 "bytes" 9 "crypto/rand" 10 "encoding/hex" 11 "io" 12 "testing" 13 14 "github.com/btcsuite/btcd/btcec/v2" 15 "github.com/ethersphere/bee/v2/pkg/crypto" 16 ) 17 18 func TestECDHCorrect(t *testing.T) { 19 t.Parallel() 20 21 key0, err := crypto.GenerateSecp256k1Key() 22 if err != nil { 23 t.Fatal(err) 24 } 25 dh0 := crypto.NewDH(key0) 26 27 key1, err := crypto.GenerateSecp256k1Key() 28 if err != nil { 29 t.Fatal(err) 30 } 31 dh1 := crypto.NewDH(key1) 32 33 salt := make([]byte, 32) 34 if _, err := io.ReadFull(rand.Reader, salt); err != nil { 35 t.Fatal(err) 36 } 37 38 sk0, err := dh0.SharedKey(&key1.PublicKey, salt) 39 if err != nil { 40 t.Fatal(err) 41 } 42 sk1, err := dh1.SharedKey(&key0.PublicKey, salt) 43 if err != nil { 44 t.Fatal(err) 45 } 46 47 if !bytes.Equal(sk0, sk1) { 48 t.Fatal("shared secrets do not match") 49 } 50 } 51 52 func TestSharedKey(t *testing.T) { 53 t.Parallel() 54 55 data, err := hex.DecodeString("c786dd84b61485de12146fd9c4c02d87e8fd95f0542765cb7fc3d2e428c0bcfa") 56 if err != nil { 57 t.Fatal(err) 58 } 59 60 privKey, err := crypto.DecodeSecp256k1PrivateKey(data) 61 if err != nil { 62 t.Fatal(err) 63 } 64 data, err = hex.DecodeString("0271e574ad8f6a6c998c84c27df18124fddd906aba9d852150da4223edde14044f") 65 if err != nil { 66 t.Fatal(err) 67 } 68 pubkey, err := btcec.ParsePubKey(data) 69 if err != nil { 70 t.Fatal(err) 71 } 72 salt, err := hex.DecodeString("cb7e692f211f8ae4f858ff56ce8a4fc0e40bae1a36f8283f0ceb6bb4be133f1e") 73 if err != nil { 74 t.Fatal(err) 75 } 76 77 dh := crypto.NewDH(privKey) 78 sk, err := dh.SharedKey(pubkey.ToECDSA(), salt) 79 if err != nil { 80 t.Fatal(err) 81 } 82 83 expectedSKHex := "9edbd3beeb48c090158ccb82d679c5ea2bcb74850d34fe55c10b32e16b822007" 84 expectedSK, err := hex.DecodeString(expectedSKHex) 85 if err != nil { 86 t.Fatal(err) 87 } 88 89 if !bytes.Equal(sk, expectedSK) { 90 t.Fatalf("incorrect shared key: expected %v, got %x", expectedSK, sk) 91 } 92 93 }