forked from forgoer/openssl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
padding.go
executable file
·79 lines (68 loc) · 1.65 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package openssl
import (
"bytes"
"errors"
)
var ErrUnPadding = errors.New("UnPadding error")
const PKCS5_PADDING = "PKCS5"
const PKCS7_PADDING = "PKCS7"
const ZEROS_PADDING = "ZEROS"
func Padding(padding string, src []byte, blockSize int) []byte {
switch padding {
case PKCS5_PADDING:
src = PKCS5Padding(src, blockSize)
case PKCS7_PADDING:
src = PKCS7Padding(src, blockSize)
case ZEROS_PADDING:
src = ZerosPadding(src, blockSize)
}
return src
}
func UnPadding(padding string, src []byte) ([]byte, error) {
switch padding {
case PKCS5_PADDING:
return PKCS5Unpadding(src)
case PKCS7_PADDING:
return PKCS7UnPadding(src)
case ZEROS_PADDING:
return ZerosUnPadding(src)
}
return src, nil
}
func PKCS5Padding(src []byte, blockSize int) []byte {
return PKCS7Padding(src, blockSize)
}
func PKCS5Unpadding(src []byte) ([]byte, error) {
return PKCS7UnPadding(src)
}
func PKCS7Padding(src []byte, blockSize int) []byte {
padding := blockSize - len(src)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(src, padtext...)
}
func PKCS7UnPadding(src []byte) ([]byte, error) {
length := len(src)
if length == 0 {
return src, ErrUnPadding
}
unpadding := int(src[length-1])
if length < unpadding {
return src, ErrUnPadding
}
return src[:(length - unpadding)], nil
}
func ZerosPadding(src []byte, blockSize int) []byte {
paddingCount := blockSize - len(src)%blockSize
if paddingCount == 0 {
return src
} else {
return append(src, bytes.Repeat([]byte{byte(0)}, paddingCount)...)
}
}
func ZerosUnPadding(src []byte) ([]byte, error) {
for i := len(src) - 1; ; i-- {
if src[i] != 0 {
return src[:i+1], nil
}
}
}