forked from lonng/nanoserver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.go
42 lines (33 loc) · 851 Bytes
/
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
package game
import (
"encoding/base64"
"fmt"
"github.com/lonnng/nano"
"github.com/lonnng/nano/session"
"github.com/xxtea/xxtea-go/xxtea"
)
var xxteaKey = []byte("7AEC4MA152BQE9HWQ7KB")
type Crypto struct {
key []byte
}
func newCrypto() *Crypto {
return &Crypto{xxteaKey}
}
func (c *Crypto) inbound(s *session.Session, msg nano.Message) error {
out, err := base64.StdEncoding.DecodeString(string(msg.Data))
if err != nil {
logger.Errorf("Inbound Error=%s, In=%s", err.Error(), string(msg.Data))
return err
}
out = xxtea.Decrypt(out, c.key)
if out == nil {
return fmt.Errorf("decrypt error=%s", err.Error())
}
msg.Data = out
return nil
}
func (c *Crypto) outbound(s *session.Session, msg nano.Message) error {
out := xxtea.Encrypt(msg.Data, c.key)
msg.Data = []byte(base64.StdEncoding.EncodeToString(out))
return nil
}