/
des.go
77 lines (57 loc) · 1.61 KB
/
des.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
package des
import (
"strconv"
"crypto/des"
"crypto/cipher"
"github.com/deatil/go-cryptobin/tool/alias"
)
// The DES block size in bytes.
const BlockSize = des.BlockSize
type KeySizeError int
func (k KeySizeError) Error() string {
return "cryptobin/twoDes: invalid key size " + strconv.Itoa(int(k))
}
type twoDESCipher struct {
cipher cipher.Block
}
// NewTwoDESCipher creates and returns a new cipher.Block.
func NewTwoDESCipher(key []byte) (cipher.Block, error) {
if len(key) != 16 {
return nil, KeySizeError(len(key))
}
key = append(key, key[:8]...)
cip, err := des.NewTripleDESCipher(key)
if err != nil {
return nil, err
}
c := new(twoDESCipher)
c.cipher = cip
return c, nil
}
func (this *twoDESCipher) BlockSize() int {
return BlockSize
}
func (this *twoDESCipher) Encrypt(dst, src []byte) {
if len(src) < BlockSize {
panic("cryptobin/twoDes: input not full block")
}
if len(dst) < BlockSize {
panic("cryptobin/twoDes: output not full block")
}
if alias.InexactOverlap(dst[:BlockSize], src[:BlockSize]) {
panic("cryptobin/twoDes: invalid buffer overlap")
}
this.cipher.Encrypt(dst, src)
}
func (this *twoDESCipher) Decrypt(dst, src []byte) {
if len(src) < BlockSize {
panic("cryptobin/twoDes: input not full block")
}
if len(dst) < BlockSize {
panic("cryptobin/twoDes: output not full block")
}
if alias.InexactOverlap(dst[:BlockSize], src[:BlockSize]) {
panic("cryptobin/twoDes: invalid buffer overlap")
}
this.cipher.Decrypt(dst, src)
}