/
crypto_aes.go
63 lines (50 loc) · 1.25 KB
/
crypto_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
package uapolicy
import (
"crypto/aes"
"crypto/cipher"
"github.com/355911097/opcua/errors"
)
const (
AESBlockSize = aes.BlockSize
AESMinPadding = 0
)
type AES struct {
KeyLength int
IV []byte
Secret []byte
}
func (a *AES) Decrypt(src []byte) ([]byte, error) {
paddedKey := make([]byte, a.KeyLength/8)
copy(paddedKey, a.Secret)
block, err := aes.NewCipher(a.Secret)
if err != nil {
return nil, err
}
if len(src) < aes.BlockSize {
return nil, errors.New("ciphertext too short")
}
// CBC mode always works in whole blocks.
if len(src)%aes.BlockSize != 0 {
return nil, errors.New("ciphertext is not a multiple of the block size")
}
dst := make([]byte, len(src))
mode := cipher.NewCBCDecrypter(block, a.IV)
mode.CryptBlocks(dst, src)
return dst, nil
}
func (a *AES) Encrypt(src []byte) ([]byte, error) {
paddedKey := make([]byte, a.KeyLength/8)
copy(paddedKey, a.Secret)
// CBC mode always works in whole blocks.
if len(src)%aes.BlockSize != 0 {
return nil, errors.New("plaintext is not a multiple of the block size")
}
block, err := aes.NewCipher(paddedKey)
if err != nil {
return nil, err
}
dst := make([]byte, len(src))
mode := cipher.NewCBCEncrypter(block, a.IV)
mode.CryptBlocks(dst, src)
return dst, nil
}