Skip to content

Commit 4db3b08

Browse files
committed
Create diffieHellmanKeyExchange.go
1 parent f86861f commit 4db3b08

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

ciphers/diffieHellmanKeyExchange.go

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"math/rand"
6+
)
7+
func main(){
8+
bit:=30
9+
/*
10+
p and g are pre-agreed constants
11+
that can be communicated over an insecure channel
12+
p should ideally be a large prime number but any integer works
13+
g should be a small integer, 2,3 works fine
14+
15+
PS: Note that the secret keys are never send over
16+
the network
17+
*/
18+
19+
p:=2+rand.Intn(1<<bit)
20+
g:=2+rand.Intn(5)
21+
22+
//Both parties choose a secret key
23+
24+
AliceSecret := 1 + rand.Intn(1<<bit)
25+
BobSecret := 1 + rand.Intn(1<<bit)
26+
27+
fmt.Printf("Alice's secret key is: %v",AliceSecret)
28+
fmt.Printf("Bob's secret key is: %v",BobSecret)
29+
30+
//Both parties send ((g^secret_key)%p)
31+
//It's not possible to determine the secretkey from the value sent
32+
33+
AliceSends :=modularExponentiation(g,AliceSecret,p)
34+
BobSends :=modularExponentiation(g,BobSecret,p)
35+
36+
fmt.Printf("Alice sends to Bob: %v",AliceSends)
37+
fmt.Printf("Bob sends to Alice: %v",BobSends)
38+
39+
//Both parties calculate the shared secret key from the value send
40+
//(value_sent^secret_key)%p
41+
//Both calculations end up with same value despite the different inputs
42+
AliceComputes :=modularExponentiation(BobSends,AliceSecret,p)
43+
BobComputes := modularExponentiation(AliceSends,BobSecret,p)
44+
45+
fmt.Printf("Alice Computes the shared secret key as: %v",AliceComputes)
46+
fmt.Printf("Bob Computes the shared secret key as: %v",BobComputes)
47+
48+
// simply confirms that the values are equal
49+
if AliceComputes == BobComputes{
50+
sharedKey:=AliceComputes
51+
fmt.Println(" Voila, shared key is",sharedKey)
52+
}
53+
54+
55+
56+
57+
}
58+
func modularExponentiation(b int, e int, mod int)int{
59+
//runs in O(log(n)) where n = e
60+
//uses exponentiation by squaring to speed up the process
61+
if mod == 1{
62+
return 0
63+
}
64+
r:=1
65+
b = b % mod
66+
for ;e>0;{
67+
if e%2==1{
68+
r=(r*b)%mod
69+
}
70+
e =e>>1
71+
b = (b*b)%mod
72+
}
73+
return r
74+
}

0 commit comments

Comments
 (0)