-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathencryption.go
114 lines (84 loc) · 2.23 KB
/
encryption.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
package block_io_go
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"errors"
)
type ecb struct {
cipher cipher.Block
}
func newECB(c cipher.Block) *ecb {
return &ecb{
cipher: c,
}
}
func (x *ecb) BlockSize() int {
return x.cipher.BlockSize()
}
func (x *ecb) EncryptBlocks(dst []byte, src []byte) error {
if len(src) % x.BlockSize() != 0 {
return errors.New("EncryptBlocks: input not a multiple of blocksize")
}
if len(dst) < len(src) {
return errors.New("EncryptBlocks: output buffer is too small")
}
for len(src) > 0 {
x.cipher.Encrypt(dst, src[:x.BlockSize()])
src = src[x.BlockSize():]
dst = dst[x.BlockSize():]
}
return nil
}
func (x *ecb) DecryptBlocks(dst []byte, src []byte) error {
if len(src) % x.BlockSize() != 0 {
return errors.New("DecryptBlocks: input not a multiple of blocksize")
}
if len(dst) < len(src) {
return errors.New("DecryptBlocks: output buffer is too small")
}
for len(src) > 0 {
x.cipher.Decrypt(dst, src[:x.BlockSize()])
src = src[x.BlockSize():]
dst = dst[x.BlockSize():]
}
return nil
}
func (x *ecb) pkcs5Padding(ciphertext []byte) []byte {
padding := x.BlockSize() - len(ciphertext) % x.BlockSize()
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func (x *ecb) pkcs5UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
func AESEncrypt(clearText []byte, key []byte) ([]byte, error) {
cipher, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(clearText) == 0 {
return nil, errors.New("AESEncrypt: Cleartext length is 0")
}
ecb := newECB(cipher)
padded := ecb.pkcs5Padding(clearText)
cipherText := make([]byte, len(padded))
ecb.EncryptBlocks(cipherText, padded)
return cipherText, nil
}
func AESDecrypt(cipherText []byte, key []byte) ([]byte, error) {
cipher, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(cipherText) == 0 {
return nil, errors.New("AESDecrypt: Ciphertext length is 0")
}
ecb := newECB(cipher)
decrypted := make([]byte, len(cipherText))
ecb.DecryptBlocks(decrypted, []byte(cipherText))
unpadded := ecb.pkcs5UnPadding(decrypted)
return unpadded, nil
}