/
aes.go
76 lines (60 loc) · 1.63 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
73
74
75
76
package crypto
/*
References:
https://gist.github.com/fracasula/38aa1a4e7481f9cedfa78a0cdd5f1865
https://golangdocs.com/aes-encryption-decryption-in-golang
*/
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
)
func AESEncrypt(plaintext []byte, iv []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return []byte(""), err
}
if string(plaintext) == "" {
return []byte(""), errors.New("string to encrypt is empty")
}
ecb := cipher.NewCBCEncrypter(block, iv)
content := []byte(plaintext)
content = PKCS5Padding(content, block.BlockSize())
crypted := make([]byte, len(content))
ecb.CryptBlocks(crypted, content)
return crypted, nil
}
func AESDecrypt(ciphertext []byte, iv []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return []byte(""), err
}
if len(ciphertext) == 0 {
return []byte(""), errors.New("ciphertext cannot be empty")
}
ecb := cipher.NewCBCDecrypter(block, iv)
decrypted := make([]byte, len(ciphertext))
ecb.CryptBlocks(decrypted, ciphertext)
return PKCS5Trimming(decrypted), nil
}
func GenerateIV() ([]byte, error) {
iv := make([]byte, aes.BlockSize)
_, err := rand.Read(iv)
if err != nil {
return []byte(""), err
}
return iv, nil
}
// ==================
// Auxiliar functions
func PKCS5Trimming(encrypt []byte) []byte {
padding := encrypt[len(encrypt)-1]
return encrypt[:len(encrypt)-int(padding)]
}
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}