Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 20 additions & 8 deletions cipher/diffiehellman/diffiehellmankeyexchange_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,22 @@ package diffiehellman

import (
"crypto/rand"
"crypto/rsa"
"math/big"
"testing"
)

// randomPrivateKey returns a uniformly random private key in the range
// [1, primeNumber-1], which is the valid range for a Diffie-Hellman secret.
func randomPrivateKey(t *testing.T) int64 {
t.Helper()
// rand.Int returns a value in [0, primeNumber-1); shift by 1 to get [1, primeNumber-1].
n, err := rand.Int(rand.Reader, big.NewInt(primeNumber-1))
if err != nil {
t.Fatalf("failed to generate random private key: %v", err)
}
return n.Int64() + 1
}

func TestDiffieHellmanKeyExchange(t *testing.T) {
t.Run("Test 1: modularExponentiation", func(t *testing.T) {
var want int64 = 9 // (3^5)mod13 = 243mod13 = 9
Expand All @@ -20,19 +32,19 @@ func TestDiffieHellmanKeyExchange(t *testing.T) {
})

t.Run("Test 2: Key Exchange", func(t *testing.T) {
// generating a small sized rsa_cipher key for testing
alicePrvKey, _ := rsa.GenerateKey(rand.Reader, 31)
bobPrvKey, _ := rsa.GenerateKey(rand.Reader, 31)
// alice and bob each pick a private key
alicePrvKey := randomPrivateKey(t)
bobPrvKey := randomPrivateKey(t)

// alice and bob generates their respective share key with their privateKey
shareKeyByAlice := GenerateShareKey(alicePrvKey.D.Int64())
shareKeyByBob := GenerateShareKey(bobPrvKey.D.Int64())
shareKeyByAlice := GenerateShareKey(alicePrvKey)
shareKeyByBob := GenerateShareKey(bobPrvKey)

// generated share key now can be exchanged even via insecure channel

// mutualKey can be computed using shared key
mutualKeyComputedByAlice := GenerateMutualKey(alicePrvKey.D.Int64(), shareKeyByBob)
mutualKeyComputedByBob := GenerateMutualKey(bobPrvKey.D.Int64(), shareKeyByAlice)
mutualKeyComputedByAlice := GenerateMutualKey(alicePrvKey, shareKeyByBob)
mutualKeyComputedByBob := GenerateMutualKey(bobPrvKey, shareKeyByAlice)

if mutualKeyComputedByAlice != mutualKeyComputedByBob {
t.Errorf("mutual key computed by alice and bob should be same, but got un-equal")
Expand Down