-
Notifications
You must be signed in to change notification settings - Fork 0
/
ecdh.go
115 lines (97 loc) · 2.55 KB
/
ecdh.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package ecdh
import (
"crypto"
"crypto/subtle"
"hash"
"io"
"sync"
"github.com/aacfactory/afssl/gmsm/kdf"
"github.com/aacfactory/afssl/gmsm/sm3"
)
type Curve interface {
GenerateKey(rand io.Reader) (*PrivateKey, error)
NewPrivateKey(key []byte) (*PrivateKey, error)
NewPublicKey(key []byte) (*PublicKey, error)
ecdh(local *PrivateKey, remote *PublicKey) ([]byte, error)
sm2mqv(sLocal, eLocal *PrivateKey, sRemote, eRemote *PublicKey) (*PublicKey, error)
sm2za(md hash.Hash, pub *PublicKey, uid []byte) ([]byte, error)
privateKeyToPublicKey(*PrivateKey) *PublicKey
}
type PublicKey struct {
curve Curve
publicKey []byte
}
func (k *PublicKey) Bytes() []byte {
var buf [133]byte
return append(buf[:0], k.publicKey...)
}
func (k *PublicKey) Equal(x crypto.PublicKey) bool {
xx, ok := x.(*PublicKey)
if !ok {
return false
}
return k.curve == xx.curve &&
subtle.ConstantTimeCompare(k.publicKey, xx.publicKey) == 1
}
func (k *PublicKey) Curve() Curve {
return k.curve
}
func (k *PublicKey) SM2ZA(md hash.Hash, uid []byte) ([]byte, error) {
return k.curve.sm2za(md, k, uid)
}
func (uv *PublicKey) SM2SharedKey(isResponder bool, kenLen int, sPub, sRemote *PublicKey, uid []byte, remoteUID []byte) ([]byte, error) {
var buffer [128]byte
copy(buffer[:], uv.publicKey[1:])
peerZ, err := sRemote.SM2ZA(sm3.New(), remoteUID)
if err != nil {
return nil, err
}
z, err := sPub.SM2ZA(sm3.New(), uid)
if err != nil {
return nil, err
}
if isResponder {
copy(buffer[64:], peerZ)
copy(buffer[96:], z)
} else {
copy(buffer[64:], z)
copy(buffer[96:], peerZ)
}
return kdf.Kdf(sm3.New(), buffer[:], kenLen), nil
}
type PrivateKey struct {
curve Curve
privateKey []byte
publicKey *PublicKey
publicKeyOnce sync.Once
}
func (k *PrivateKey) ECDH(remote *PublicKey) ([]byte, error) {
return k.curve.ecdh(k, remote)
}
func (k *PrivateKey) SM2MQV(eLocal *PrivateKey, sRemote, eRemote *PublicKey) (*PublicKey, error) {
return k.curve.sm2mqv(k, eLocal, sRemote, eRemote)
}
func (k *PrivateKey) Bytes() []byte {
var buf [66]byte
return append(buf[:0], k.privateKey...)
}
func (k *PrivateKey) Equal(x crypto.PrivateKey) bool {
xx, ok := x.(*PrivateKey)
if !ok {
return false
}
return k.curve == xx.curve &&
subtle.ConstantTimeCompare(k.privateKey, xx.privateKey) == 1
}
func (k *PrivateKey) Curve() Curve {
return k.curve
}
func (k *PrivateKey) PublicKey() *PublicKey {
k.publicKeyOnce.Do(func() {
k.publicKey = k.curve.privateKeyToPublicKey(k)
})
return k.publicKey
}
func (k *PrivateKey) Public() crypto.PublicKey {
return k.PublicKey()
}