-
Notifications
You must be signed in to change notification settings - Fork 352
/
Copy pathdh.go
54 lines (45 loc) · 945 Bytes
/
dh.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package base
import (
"math/big"
"math/rand"
)
type (
Dh struct{
q big.Int//素数q
a big.Int//q的原根a
x big.Int//私钥
Y1 big.Int//自己公钥
Y2 big.Int//对方公钥
}
IDh interface {
Init()
generatePrik()//生成私钥
generatePubk()//生成公钥
ExchangePubk(key int64)//交换公钥
PubKey() int64//公钥
ShareKey()int64//生成共享密钥
}
)
func (this *Dh) Init(){
this.q = *big.NewInt(97)
this.a = *big.NewInt(5)
this.generatePrik()
this.generatePubk()
}
func (this *Dh) generatePrik(){
r := big.NewInt(int64(rand.Int()))
this.x.Mod(r, &this.q)
this.x.Add(&this.x, big.NewInt(1))
}
func (this *Dh) generatePubk(){
this.Y1.Exp(&this.a, &this.x, &this.q)
}
func (this *Dh) ExchangePubk(key int64){
this.Y2 = *big.NewInt(key)
}
func (this *Dh) PubKey() int64{
return this.Y1.Int64()
}
func (this *Dh) ShareKey() int64{
return big.NewInt(0).Exp(&this.Y2, &this.x, &this.q).Int64()
}