/
padding.go
61 lines (47 loc) · 1.14 KB
/
padding.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
package cfg
import (
"bytes"
"crypto/rand"
)
func pkcs5Trimming(encrypt []byte) ([]byte, error) {
var (
length = len(encrypt)
cipherLen = int(encrypt[length-1])
)
if length < cipherLen {
return nil, ErrKey
}
return encrypt[:length-cipherLen], nil
}
func pkcs5Padding(cipherText []byte, blockSize int) []byte {
padding := blockSize - len(cipherText)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(cipherText, padText...)
}
func Padding(cipherText []byte, blockSize int) []byte {
var (
padding = getPaddingSize(cipherText, blockSize)
padData = make([]byte, padding-1)
)
_, _ = rand.Read(padData)
// nolint
padData = append(padData, byte(padding))
return append(cipherText, padData...)
}
func UnPadding(cipherText []byte) ([]byte, error) {
var (
length = len(cipherText)
cipherLen = int(cipherText[length-1])
)
if length < cipherLen {
return nil, ErrKey
}
return cipherText[:length-cipherLen], nil
}
func getPaddingSize(cipherText []byte, blockSize int) int {
remainder := len(cipherText) % blockSize
if remainder == 0 {
return blockSize
}
return blockSize - remainder
}