| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
package dh |
| 8 |
|
| 9 |
import ( |
| 10 |
cryptorand "crypto/rand" |
| 11 |
"errors" |
| 12 |
"io" |
| 13 |
"math/big" |
| 14 |
) |
| 15 |
|
| 16 |
var zero *big.Int = big.NewInt(0) |
| 17 |
var one *big.Int = big.NewInt(1) |
| 18 |
var two *big.Int = big.NewInt(2) |
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
func IsSafePrimeGroup(g *Group, n int) bool { |
| 27 |
q := new(big.Int).Sub(g.P, one) |
| 28 |
q = q.Div(q, two) |
| 29 |
return q.ProbablyPrime(n) |
| 30 |
} |
| 31 |
|
| 32 |
|
| 33 |
type PublicKey *big.Int |
| 34 |
|
| 35 |
|
| 36 |
type PrivateKey *big.Int |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
type Group struct { |
| 41 |
P *big.Int |
| 42 |
G *big.Int |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
func (g *Group) GenerateKey(rand io.Reader) (private PrivateKey, public PublicKey, err error) { |
| 48 |
if g.P == nil { |
| 49 |
panic("crypto/dh: group prime is nil") |
| 50 |
} |
| 51 |
if g.G == nil { |
| 52 |
panic("crypto/dh: group generator is nil") |
| 53 |
} |
| 54 |
if rand == nil { |
| 55 |
rand = cryptorand.Reader |
| 56 |
} |
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
min := big.NewInt(int64(g.P.BitLen() + 1)) |
| 63 |
bytes := make([]byte, (g.P.BitLen()+7)/8) |
| 64 |
|
| 65 |
for private == nil { |
| 66 |
_, err = io.ReadFull(rand, bytes) |
| 67 |
if err != nil { |
| 68 |
private = nil |
| 69 |
return |
| 70 |
} |
| 71 |
|
| 72 |
|
| 73 |
bytes[0] = 0 |
| 74 |
if private == nil { |
| 75 |
private = new(big.Int) |
| 76 |
} |
| 77 |
(*private).SetBytes(bytes) |
| 78 |
if (*private).Cmp(min) < 0 { |
| 79 |
private = nil |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
public = new(big.Int).Exp(g.G, private, g.P) |
| 84 |
return |
| 85 |
} |
| 86 |
|
| 87 |
|
| 88 |
func (g *Group) PublicKey(private PrivateKey) (public PublicKey) { |
| 89 |
public = new(big.Int).Exp(g.G, private, g.P) |
| 90 |
return |
| 91 |
} |
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
func (g *Group) Check(peersPublic PublicKey) (err error) { |
| 97 |
if !((*peersPublic).Cmp(zero) >= 0 && (*peersPublic).Cmp(g.P) == -1) { |
| 98 |
err = errors.New("peer's public is not a possible group element") |
| 99 |
} |
| 100 |
return |
| 101 |
} |
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
func (g *Group) ComputeSecret(private PrivateKey, peersPublic PublicKey) (secret *big.Int) { |
| 106 |
secret = new(big.Int).Exp(peersPublic, private, g.P) |
| 107 |
return |
| 108 |
} |