forked from Terry-Mao/goim
-
Notifications
You must be signed in to change notification settings - Fork 3
/
aes.go
55 lines (49 loc) · 1.04 KB
/
aes.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
package aes
import (
"crypto/cipher"
"errors"
)
var (
ErrBlockSize = errors.New("input not full blocks")
ErrOutputSize = errors.New("output smaller than input")
)
func encryptBlocks(b cipher.Block, src, dst []byte) error {
if len(src)%b.BlockSize() != 0 {
return ErrBlockSize
}
if len(dst) < len(src) {
return ErrOutputSize
}
for len(src) > 0 {
b.Encrypt(dst, src[:b.BlockSize()])
src = src[b.BlockSize():]
dst = dst[b.BlockSize():]
}
return nil
}
func decryptBlocks(b cipher.Block, dst, src []byte) error {
if len(src)%b.BlockSize() != 0 {
return ErrBlockSize
}
if len(dst) < len(src) {
return ErrOutputSize
}
for len(src) > 0 {
b.Decrypt(dst, src[:b.BlockSize()])
src = src[b.BlockSize():]
dst = dst[b.BlockSize():]
}
return nil
}
func ECBEncrypt(b cipher.Block, src []byte) (dst []byte, err error) {
// use same buf
dst = src
err = encryptBlocks(b, dst, src)
return
}
func ECBDecrypt(b cipher.Block, src []byte) (dst []byte, err error) {
// use same buf
dst = src
err = decryptBlocks(b, dst, src)
return
}