-
Notifications
You must be signed in to change notification settings - Fork 48
/
cbc.go
executable file
·54 lines (41 loc) · 1.23 KB
/
cbc.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
package openssl
import (
"bytes"
"crypto/cipher"
)
// CBCEncrypt
func CBCEncrypt(block cipher.Block, src, iv []byte, padding string) ([]byte, error) {
blockSize := block.BlockSize()
src = Padding(padding, src, blockSize)
encryptData := make([]byte, len(src))
if len(iv) != block.BlockSize() {
// auto pad length to block size
iv = cbcIVPending(iv, block.BlockSize())
//return nil, errors.New("CBCEncrypt: IV length must equal block size")
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(encryptData, src)
return encryptData, nil
}
// CBCDecrypt
func CBCDecrypt(block cipher.Block, src, iv []byte, padding string) ([]byte, error) {
dst := make([]byte, len(src))
if len(iv) != block.BlockSize() {
// auto pad length to block size
iv = cbcIVPending(iv, block.BlockSize())
//return nil, errors.New("CBCDecrypt: IV length must equal block size")
}
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(dst, src)
return UnPadding(padding, dst)
}
// cbcIVPending auto pad length to block size
func cbcIVPending(iv []byte, blockSize int) []byte {
k := len(iv)
if k < blockSize {
return append(iv, bytes.Repeat([]byte{0}, blockSize-k)...)
} else if k > blockSize {
return iv[0:blockSize]
}
return iv
}