-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcipher.go
59 lines (51 loc) · 1.26 KB
/
cipher.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
package shadowsocks
import (
"crypto/md5"
"fmt"
"net"
"sort"
"strings"
)
type ConnCipher interface {
StreamConn(net.Conn) net.Conn
Decrypt(dist, src []byte) (n int, err error)
Encrypt(dist, src []byte) (n int, err error)
}
var registerCipher = map[string]func(password string) (ConnCipher, error){}
func RegisterCipher(method string, fun func(password string) (ConnCipher, error)) {
registerCipher[strings.ToLower(method)] = fun
}
func CipherList() []string {
list := make([]string, 0, len(registerCipher))
for name := range registerCipher {
list = append(list, name)
}
sort.Strings(list)
return list
}
func IsCipher(method string) bool {
_, ok := registerCipher[method]
return ok
}
// NewCipher creates a cipher that can be used in Dial()
func NewCipher(method, password string) (c ConnCipher, err error) {
method = strings.ToLower(method)
gen, ok := registerCipher[method]
if ok {
return gen(password)
}
return nil, fmt.Errorf("unsupported encryption method: %s", method)
}
// key-derivation function from original Shadowsocks
func KDF(password string, keyLen int) []byte {
var b, prev []byte
h := md5.New()
for len(b) < keyLen {
h.Write(prev)
h.Write([]byte(password))
b = h.Sum(b)
prev = b[len(b)-h.Size():]
h.Reset()
}
return b[:keyLen]
}