-
Notifications
You must be signed in to change notification settings - Fork 2
/
padding.go
89 lines (76 loc) · 1.76 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
80
81
82
83
84
85
86
87
88
89
package method
import (
"errors"
"git.golaxy.org/framework/net/gtp"
)
// Padding 填充方案
type Padding interface {
// Pad 填充
Pad(buf []byte, ori int) error
// Unpad 解除填充
Unpad(padded []byte) ([]byte, error)
}
// NewPadding 创建填充方案
func NewPadding(pm gtp.PaddingMode) (Padding, error) {
switch pm {
case gtp.PaddingMode_Pkcs7:
return _Pkcs7{}, nil
case gtp.PaddingMode_X923:
return _X923{}, nil
default:
return nil, ErrInvalidMethod
}
}
type _Pkcs7 struct{}
// Pad 填充
func (_Pkcs7) Pad(buf []byte, ori int) error {
padLen := len(buf) - ori
if padLen <= 0 || padLen > 0xff {
return errors.New("pkcs7: wrong pad length")
}
for i := 0; i < padLen; i++ {
buf[ori+i] = byte(padLen)
}
return nil
}
// Unpad 解除填充
func (_Pkcs7) Unpad(padded []byte) ([]byte, error) {
padLen := padded[len(padded)-1]
padPos := len(padded) - int(padLen)
if padPos < 0 {
return nil, errors.New("pkcs7: wrong pad pos")
}
for i := len(padded) - 1; i >= padPos; i-- {
if padded[i] != padLen {
return nil, errors.New("pkcs7: incorrect padded")
}
}
return padded[:padPos], nil
}
type _X923 struct{}
// Pad 填充
func (_X923) Pad(buf []byte, ori int) error {
padLen := len(buf) - ori
if padLen <= 0 || padLen > 0xff {
return errors.New("x923: wrong pad length")
}
for i := 0; i < padLen-1; i++ {
buf[ori+i] = 0
}
buf[ori+padLen-1] = byte(padLen)
return nil
}
// Unpad 解除填充
func (_X923) Unpad(padded []byte) ([]byte, error) {
padLen := padded[len(padded)-1]
padPos := len(padded) - int(padLen)
if padPos < 0 {
return nil, errors.New("x923: wrong pad pos")
}
for i := len(padded) - 2; i >= padPos; i-- {
if padded[i] != 0 {
return nil, errors.New("x923: incorrect padded")
}
}
return padded[:padPos], nil
}