-
Notifications
You must be signed in to change notification settings - Fork 8
/
aes_cbc_pkcs7_cipher.go
48 lines (40 loc) · 1.06 KB
/
aes_cbc_pkcs7_cipher.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
package ecies
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
)
type AesCbcPkcs7Cipher struct {
iv []byte
}
func NewAesCbcPkcs7Cipher() *AesCbcPkcs7Cipher {
return &AesCbcPkcs7Cipher{
iv: make([]byte, 16), // IV For CBC, an IV filled with zero means no IV
}
}
func (aesCbcPkcs7Cipher *AesCbcPkcs7Cipher) Encrypt(msg []byte, key []byte) ([]byte, error) {
aes, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
paddingMsg := pkcs7Pad(msg, aes.BlockSize())
cipherMsg := make([]byte, len(paddingMsg))
cbc := cipher.NewCBCEncrypter(aes, aesCbcPkcs7Cipher.iv)
cbc.CryptBlocks(cipherMsg, paddingMsg)
return cipherMsg, nil
}
func (aesCbcPkcs7Cipher *AesCbcPkcs7Cipher) Decrypt(encMsg []byte, key []byte) ([]byte, error) {
aes, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
cbc := cipher.NewCBCDecrypter(aes, aesCbcPkcs7Cipher.iv)
paddingMsg := make([]byte, len(encMsg))
cbc.CryptBlocks(paddingMsg, encMsg)
return pkcs7Unpad(paddingMsg)
}
func randomBytes(n int) []byte {
bytes := make([]byte, n)
rand.Read(bytes)
return bytes
}