forked from libp2p/go-libp2p-noise
-
Notifications
You must be signed in to change notification settings - Fork 3
/
crypto.go
60 lines (54 loc) · 1.44 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
package noise
import (
"errors"
ik "github.com/ChainSafe/go-libp2p-noise/ik"
xx "github.com/ChainSafe/go-libp2p-noise/xx"
)
func (s *secureSession) Encrypt(plaintext []byte) (ciphertext []byte, err error) {
if s.xx_complete {
if s.initiator {
cs := s.xx_ns.CS1()
_, ciphertext = xx.EncryptWithAd(cs, nil, plaintext)
} else {
cs := s.xx_ns.CS2()
_, ciphertext = xx.EncryptWithAd(cs, nil, plaintext)
}
} else if s.ik_complete {
if s.initiator {
cs := s.ik_ns.CS1()
_, ciphertext = ik.EncryptWithAd(cs, nil, plaintext)
} else {
cs := s.ik_ns.CS2()
_, ciphertext = ik.EncryptWithAd(cs, nil, plaintext)
}
} else {
return nil, errors.New("encrypt err: haven't completed handshake")
}
return ciphertext, nil
}
func (s *secureSession) Decrypt(ciphertext []byte) (plaintext []byte, err error) {
var ok bool
if s.xx_complete {
if s.initiator {
cs := s.xx_ns.CS2()
_, plaintext, ok = xx.DecryptWithAd(cs, nil, ciphertext)
} else {
cs := s.xx_ns.CS1()
_, plaintext, ok = xx.DecryptWithAd(cs, nil, ciphertext)
}
} else if s.ik_complete {
if s.initiator {
cs := s.ik_ns.CS2()
_, plaintext, ok = ik.DecryptWithAd(cs, nil, ciphertext)
} else {
cs := s.ik_ns.CS1()
_, plaintext, ok = ik.DecryptWithAd(cs, nil, ciphertext)
}
} else {
return nil, errors.New("decrypt err: haven't completed handshake")
}
if !ok {
return nil, errors.New("decrypt err: could not decrypt")
}
return plaintext, nil
}