-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathutils.go
116 lines (95 loc) · 2.43 KB
/
utils.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
116
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/binary"
"errors"
"io"
"net"
"os"
"runtime/debug"
"strconv"
"github.com/polevpn/anyvalue"
"github.com/polevpn/elog"
)
var ServerAesKey = []byte{0x75, 0xf3, 0xfe, 0x63, 0x18, 0x1f, 0x5c, 0x27, 0xab, 0x7c, 0xad, 0x4d, 0x7b, 0xf2, 0x59, 0xd0}
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func PKCS7UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
if length-unpadding <= 0 {
return origData
}
return origData[:(length - unpadding)]
}
//AES加密
func AesEncrypt(origData, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
origData = PKCS7Padding(origData, blockSize)
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted, origData)
return crypted, nil
}
//AES解密
func AesDecrypt(crypted, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
origData := make([]byte, len(crypted))
blockMode.CryptBlocks(origData, crypted)
origData = PKCS7UnPadding(origData)
return origData, nil
}
func GetConfig(configfile string) (*anyvalue.AnyValue, error) {
f, err := os.Open(configfile)
if err != nil {
return nil, err
}
return anyvalue.NewFromJsonReader(f)
}
func ReadPacket(conn net.Conn) ([]byte, error) {
prefetch := make([]byte, 2)
_, err := io.ReadFull(conn, prefetch)
if err != nil {
return nil, err
}
len := binary.BigEndian.Uint16(prefetch)
if len < POLE_PACKET_HEADER_LEN {
return nil, errors.New("invalid pkt len=" + strconv.Itoa(int(len)))
}
pkt := make([]byte, len)
copy(pkt, prefetch)
_, err = io.ReadFull(conn, pkt[2:])
if err != nil {
return nil, err
}
return pkt, nil
}
func PanicHandler() {
if err := recover(); err != nil {
elog.Error("Panic Exception:", err)
elog.Error(string(debug.Stack()))
}
}
func PanicHandlerExit() {
if err := recover(); err != nil {
elog.Error("Panic Exception:", err)
elog.Error(string(debug.Stack()))
elog.Error("************Program Exit************")
elog.Flush()
os.Exit(0)
}
}