-
Notifications
You must be signed in to change notification settings - Fork 5
/
des_key.go
63 lines (54 loc) · 1.11 KB
/
des_key.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
package codec
import (
"bytes"
"crypto/des"
)
func newDESKey() *desKey {
return &desKey{key: NewSafeKeys(), keyFixer: FixedDESKey}
}
type desKey struct {
key *SafeKeys
keyFixer KeyFixer
}
func (a *desKey) SetKeyFixer(fixer KeyFixer) {
a.keyFixer = fixer
}
func (a *desKey) GetKey(key []byte) []byte {
ckey := string(key)
k, ok := a.key.Get(ckey)
if !ok {
k = a.GenKey(key)
a.key.Set(ckey, k)
}
return k
}
func (a *desKey) GenKey(key []byte) []byte {
if a.keyFixer == nil {
return FixedDESKey(des.BlockSize, key)
}
return a.keyFixer(des.BlockSize, key)
}
func GenDESKey(key []byte) []byte {
return FixedDESKey(des.BlockSize, key)
}
var FixedDESKey = FixedKeyByRepeatContent
func FixedKeyByRepeatContent(keyLen int, key []byte) []byte {
if len(key) == keyLen {
return key
}
k := make([]byte, keyLen)
length := len(key)
if length == 0 {
copy(k, bytes.Repeat([]byte(` `), keyLen))
} else if length < keyLen {
div := keyLen / length
mod := keyLen % length
for i := 0; i < div; i++ {
copy(k[length*i:], key)
}
copy(k[length*div:], key[:mod])
} else {
copy(k, key)
}
return k
}