-
Notifications
You must be signed in to change notification settings - Fork 3
/
des.go
108 lines (103 loc) · 2.23 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
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
package cryptlib
import (
"crypto/des"
"encoding/base64"
"errors"
)
func EntryptDesECB(data, key []byte) (string,error) {
if len(key) > 8 {
key = key[:8]
}
block, err := des.NewCipher(key)
if err != nil {
return "",err
}
bs := block.BlockSize()
data = PKCS5Padding(data, bs)
if len(data)%bs != 0 {
return "",errors.New("EntryptDesECB Need a multiple of the blocksize")
}
out := make([]byte, len(data))
dst := out
for len(data) > 0 {
block.Encrypt(dst, data[:bs])
data = data[bs:]
dst = dst[bs:]
}
return base64.StdEncoding.EncodeToString(out),nil
}
func EntryptDesECBByte(data, key []byte) ([]byte,error) {
if len(key) > 8 {
key = key[:8]
}
block, err := des.NewCipher(key)
if err != nil {
return nil,err
}
bs := block.BlockSize()
data = PKCS5Padding(data, bs)
if len(data)%bs != 0 {
return nil,errors.New("EntryptDesECB Need a multiple of the blocksize")
}
out := make([]byte, len(data))
dst := out
for len(data) > 0 {
block.Encrypt(dst, data[:bs])
data = data[bs:]
dst = dst[bs:]
}
buf := make([]byte, base64.StdEncoding.EncodedLen(len(out)))
base64.StdEncoding.Encode(buf, out)
return buf,nil
}
func DecryptDESECB(d string, key []byte) (string,error) {
data, err := base64.StdEncoding.DecodeString(d)
if err != nil {
return "",err
}
if len(key) > 8 {
key = key[:8]
}
block, err := des.NewCipher(key)
if err != nil {
return "",err
}
bs := block.BlockSize()
if len(data)%bs != 0 {
return "",errors.New("DecryptDES crypto/cipher: input not full blocks")
}
out := make([]byte, len(data))
dst := out
for len(data) > 0 {
block.Decrypt(dst, data[:bs])
data = data[bs:]
dst = dst[bs:]
}
out = PKCS5UnPadding(out)
return string(out),nil
}
func DecryptDESECBByte(d string, key []byte) ([]byte,error) {
data, err := base64.StdEncoding.DecodeString(d)
if err != nil {
return nil,err
}
if len(key) > 8 {
key = key[:8]
}
block, err := des.NewCipher(key)
if err != nil {
return nil,err
}
bs := block.BlockSize()
if len(data)%bs != 0 {
return nil,errors.New("DecryptDES crypto/cipher: input not full blocks")
}
out := make([]byte, len(data))
dst := out
for len(data) > 0 {
block.Decrypt(dst, data[:bs])
data = data[bs:]
dst = dst[bs:]
}
return PKCS5UnPadding(out),nil
}