-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
121 lines (96 loc) · 2.08 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
117
118
119
120
121
package main
import (
"bytes"
"crypto/aes"
"log"
"math/rand"
)
func xorEncryptBytes(one, key []byte) []byte {
var result bytes.Buffer
keyLen := len(key)
bufLen := len(one)
for i := 0; i < bufLen; i += keyLen {
for k := 0; k < keyLen && i+k < bufLen; k++ {
result.WriteByte(one[i+k] ^ key[k])
}
}
return result.Bytes()
}
func AddPadding(data []byte, blocksize int) []byte {
var padded bytes.Buffer
var pads int
padded.Write(data)
if len(data) < blocksize {
pads = blocksize - len(data)
} else {
pads = blocksize - (len(data) % blocksize)
}
if pads == 0 {
pads = 16
}
for i := 0; i < pads; i++ {
padded.WriteByte(byte(pads))
}
return padded.Bytes()
}
func StripPadding(data []byte) []byte {
length := int(data[len(data)-1])
stripped := data[:len(data)-length]
return stripped
}
func VerifyPadding(data []byte) bool {
length := len(data)
pads := data[length-1]
expectedPadding := make([]byte, pads)
for i, _ := range expectedPadding {
expectedPadding[i] = pads
}
return bytes.Equal(expectedPadding, data[length-int(pads):length])
}
func RandomKey(length int) []byte {
var key bytes.Buffer
for ; length > 0; length-- {
key.WriteByte(byte(rand.Int()))
}
return key.Bytes()
}
func CBCEncrypt(key, data, IV []byte) []byte {
c, err := aes.NewCipher(key)
if err != nil {
log.Fatal(err)
}
encrypter := NewCBCEncrypter(c, IV)
p := make([]byte, len(data))
encrypter.CryptBlocks(p, data)
return p
}
func ECBDecrypt(key, data []byte) []byte {
c, err := aes.NewCipher(key)
if err != nil {
log.Fatal(err)
}
decrypter := NewECBDecrypter(c)
p := make([]byte, len(data))
decrypter.CryptBlocks(p, data)
return p
}
func CBCDecrypt(key, data, IV []byte) []byte {
c, err := aes.NewCipher(key)
if err != nil {
log.Fatal(err)
}
decrypter := NewCBCDecrypter(c, IV)
p := make([]byte, len(data))
decrypter.CryptBlocks(p, data)
return p
}
func ECBEncrypt(key, data []byte) []byte {
c, err := aes.NewCipher(key)
if err != nil {
log.Fatal(err)
}
encrypter := NewECBEncrypter(c)
p := make([]byte, len(data))
encrypter.CryptBlocks(p, data)
return p
}