-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpadding.go
87 lines (64 loc) · 1.86 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
// Copyright 2024 FishGoddess. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package cryptox
import "fmt"
var (
PaddingNone Padding = paddingNone{}
PaddingZero Padding = paddingZero{}
PaddingPKCS5 Padding = paddingPKCS7{} // PKCS5 is actually the same as pkcs7.
PaddingPKCS7 Padding = paddingPKCS7{}
)
// Padding paddings and undo paddings to a byte slice.
type Padding interface {
Padding(bs Bytes, blockSize int) Bytes
UndoPadding(bs Bytes, blockSize int) (Bytes, error)
}
type paddingNone struct{}
func (paddingNone) Padding(bs Bytes, blockSize int) Bytes {
return bs
}
func (paddingNone) UndoPadding(bs Bytes, blockSize int) (Bytes, error) {
return bs, nil
}
type paddingZero struct{}
func (paddingZero) Padding(bs Bytes, blockSize int) Bytes {
padding := blockSize - (len(bs) % blockSize)
for i := 0; i < padding; i++ {
bs = append(bs, 0)
}
return bs
}
func (paddingZero) UndoPadding(bs Bytes, blockSize int) (Bytes, error) {
length := len(bs)
var i int
for i = length; i > 0; i-- {
if bs[i-1] != 0 {
break
}
// Remove blockSize of bytes at most due to padding blockSize of bytes at most.
if length-i >= blockSize {
break
}
}
return bs[:i], nil
}
type paddingPKCS7 struct{}
func (paddingPKCS7) Padding(bs Bytes, blockSize int) Bytes {
padding := blockSize - (len(bs) % blockSize)
for i := 0; i < padding; i++ {
bs = append(bs, byte(padding))
}
return bs
}
func (paddingPKCS7) UndoPadding(bs Bytes, blockSize int) (Bytes, error) {
length := len(bs)
number := int(bs[length-1])
if number > length {
return nil, fmt.Errorf("cryptox: unpadding pkcs7 number %d > length %d", number, length)
}
if number > blockSize {
return nil, fmt.Errorf("cryptox: unpadding pkcs7 number %d > blockSize %d", number, blockSize)
}
return bs[:length-number], nil
}