/
aes.go
52 lines (39 loc) · 1.1 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
package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/sha256"
"errors"
)
func ToAesKey(pwd []byte) []byte {
hash := sha256.Sum256(pwd)
double := sha256.Sum256(hash[:])
return double[:]
}
func AesEncrypt(plaintext []byte, key []byte, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, errors.New("invalid decrypt key")
}
blockMode := cipher.NewCBCEncrypter(block, iv)
cipherText := make([]byte, len(plaintext))
blockMode.CryptBlocks(cipherText, plaintext)
return cipherText, nil
}
func AesDecrypt(cipherText []byte, key []byte, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, errors.New("invalid decrypt key")
}
blockSize := block.BlockSize()
if len(cipherText) < blockSize {
return nil, errors.New("cipherText too short")
}
if len(cipherText)%blockSize != 0 {
return nil, errors.New("cipherText is not a multiple of the block size")
}
blockModel := cipher.NewCBCDecrypter(block, iv)
plaintext := make([]byte, len(cipherText))
blockModel.CryptBlocks(plaintext, cipherText)
return plaintext, nil
}