summaryrefslogtreecommitdiffstats
path: root/lib/dh.go
blob: 0782033a57cec38f6f8974d2dca7ebad7f4aa1bb (plain) (blame)
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
// Copyright © 2021 siddharth <s@ricketyspace.net>
// SPDX-License-Identifier: ISC

package lib

import "math/big"

type DH struct {
	p  *big.Int
	g  *big.Int
	pk *big.Int // Private key
}

func NewDH(ps, gs string) (*DH, bool) {
	p, ok := new(big.Int).SetString(StripSpaceChars(ps), 16)
	if !ok {
		return nil, false
	}
	g, ok := new(big.Int).SetString(StripSpaceChars(gs), 16)
	if !ok {
		return nil, false
	}

	// Init DH.
	dh := new(DH)
	dh.p = p
	dh.g = g
	dh.pk = big.NewInt(RandomInt(1, 10000000))
	return dh, true
}

// Return our public key.
func (dh *DH) Pub() *big.Int {
	return new(big.Int).Exp(dh.g, dh.pk, dh.p)
}

// Return shared secret between us and the other party.
// `pub` is the other party's public key.
func (dh *DH) SharedSecret(pub *big.Int) *big.Int {
	return new(big.Int).Exp(pub, dh.pk, dh.p)
}