-
Notifications
You must be signed in to change notification settings - Fork 1
/
aes.go
72 lines (59 loc) · 1.73 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package crypt
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"io"
)
func PKCS5Padding(src []byte, block_size int) []byte {
padding := block_size - len(src)%block_size
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(src, padtext...)
}
func PKCS5UnPadding(src []byte, block_size int) ([]byte, error) {
length := len(src)
padding := int(src[length-1])
if padding < 0 || padding > length {
return nil, errors.New("PKCS5UnPadding error")
}
return src[:length-padding], nil
}
func Encrypt(block cipher.Block, plaintext []byte, key []byte) ([]byte, error) {
block_size := block.BlockSize()
plaintext = PKCS5Padding(plaintext, block_size)
ciphertext := make([]byte, block_size+len(plaintext))
iv := ciphertext[:block_size]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[block_size:], plaintext)
return ciphertext, nil
}
func Decrypt(block cipher.Block, ciphertext []byte, key []byte) ([]byte, error) {
block_size := block.BlockSize()
if len(ciphertext) < block_size {
return nil, errors.New("Decrypt failed: uncomplete ciphertext")
}
iv := ciphertext[:block_size]
ciphertext = ciphertext[block_size:]
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertext, ciphertext)
return PKCS5UnPadding(ciphertext, block_size)
}
func AesEncrypt(plaintext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
return Encrypt(block, plaintext, key)
}
func AesDecrypt(ciphertext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
return Decrypt(block, ciphertext, key)
}