-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathkem.go
86 lines (68 loc) · 1.65 KB
/
kem.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package dhpals
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/sha256"
"io"
"math/big"
"github.com/dnkolegov/dhpals/dhgroup"
)
type KEMPrivateKey interface{}
type KEMPublicKey interface{}
type dhkemScheme struct {
group dhgroup.DHScheme
}
func (g dhkemScheme) GenerateKeyPair(rand io.Reader) (KEMPrivateKey, KEMPublicKey, error) {
key, _ := g.group.GenerateKey(rand)
return key.Private, key.Public, nil
}
func (g dhkemScheme) Encap(priv KEMPrivateKey, pub KEMPublicKey, payload []byte) []byte {
dhPriv, ok := priv.(*big.Int)
if !ok {
panic("Private key not suitable for DH")
}
dhPub, ok := pub.(*big.Int)
if !ok {
panic("Public key not suitable for DH")
}
zz := new(big.Int).Exp(dhPub, dhPriv, g.group.DHParams().P)
k := sha256.Sum256(zz.Bytes())
block, err := aes.NewCipher(k[:])
if err != nil {
panic(err.Error())
}
nonce := bytes.Repeat([]byte{1}, 12)
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
ct := aesgcm.Seal(nil, nonce, payload, nil)
return ct
}
func (g dhkemScheme) Decap(priv KEMPrivateKey, pub KEMPublicKey, ct []byte) []byte {
dhPriv, ok := priv.(*big.Int)
if !ok {
panic("Private key not suitable for DH")
}
dhPub, ok := pub.(*big.Int)
if !ok {
panic("Public key not suitable for DH")
}
zz := new(big.Int).Exp(dhPub, dhPriv, g.group.DHParams().P)
k := sha256.Sum256(zz.Bytes())
block, err := aes.NewCipher(k[:])
if err != nil {
panic(err.Error())
}
nonce := bytes.Repeat([]byte{1}, 12)
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
payload, err := aesgcm.Open(nil, nonce, ct, nil)
if err != nil {
panic(err)
}
return payload
}