-
Notifications
You must be signed in to change notification settings - Fork 129
/
Copy pathcrypto.go
77 lines (61 loc) · 1.66 KB
/
crypto.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
package liteclient
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/ed25519"
"crypto/sha256"
"errors"
"github.com/oasisprotocol/curve25519-voi/curve"
ed25519crv "github.com/oasisprotocol/curve25519-voi/primitives/ed25519"
"github.com/oasisprotocol/curve25519-voi/primitives/x25519"
)
func keyID(key []byte) ([]byte, error) {
if len(key) != 32 {
return nil, errors.New("key not 32 bytes")
}
// https://github.com/ton-blockchain/ton/blob/24dc184a2ea67f9c47042b4104bbb4d82289fac1/crypto/block/check-proof.cpp#L488
magic := []byte{0xc6, 0xb4, 0x13, 0x48}
hash := sha256.New()
hash.Write(magic)
hash.Write(key)
s := hash.Sum(nil)
return s, nil
}
// generate encryption key based on our and server key, ECDH algorithm
func sharedKey(ourKey ed25519.PrivateKey, serverKey ed25519.PublicKey) ([]byte, error) {
comp, err := curve.NewCompressedEdwardsYFromBytes(serverKey)
if err != nil {
return nil, err
}
ep, err := curve.NewEdwardsPoint().SetCompressedY(comp)
if err != nil {
return nil, err
}
mp := curve.NewMontgomeryPoint().SetEdwards(ep)
bb := x25519.EdPrivateKeyToX25519(ed25519crv.PrivateKey(ourKey))
key, err := x25519.X25519(bb, mp[:])
if err != nil {
return nil, err
}
return key, nil
}
func newCipherCtr(key, iv []byte) (cipher.Stream, error) {
c, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
return cipher.NewCTR(c, iv), nil
}
func validatePacket(data []byte, recvChecksum []byte) error {
if len(data) < 32 {
return errors.New("too small packet")
}
hash := sha256.New()
hash.Write(data)
checksum := hash.Sum(nil)
if !bytes.Equal(recvChecksum, checksum) {
return errors.New("checksum packet")
}
return nil
}