forked from solidgate-tech/go-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encryption.go
51 lines (40 loc) · 956 Bytes
/
encryption.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
package solidgate
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"io"
)
func pkcs7Pad(b []byte, blockSize int) ([]byte, error) {
if blockSize <= 0 {
return nil, errors.New("block size less than 0")
}
if b == nil {
return nil, errors.New("empty data to encrypt")
}
n := blockSize - (len(b) % blockSize)
pb := make([]byte, len(b)+n)
copy(pb, b)
copy(pb[len(b):], bytes.Repeat([]byte{byte(n)}, n))
return pb, nil
}
func EncryptCBC(key, data []byte) ([]byte, error) {
data, err := pkcs7Pad(data, aes.BlockSize)
if err != nil {
return nil, err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
cipherText := make([]byte, aes.BlockSize+len(data))
iv := cipherText[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(cipherText[aes.BlockSize:], data)
return cipherText, nil
}