diff options
-rw-r--r-- | crypto/pkcs7/padding.go | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/crypto/pkcs7/padding.go b/crypto/pkcs7/padding.go new file mode 100644 index 0000000..1f90643 --- /dev/null +++ b/crypto/pkcs7/padding.go | |||
@@ -0,0 +1,41 @@ | |||
1 | package pkcs7 | ||
2 | |||
3 | // Shamelessly stolen from: https://wgallagher86.medium.com/pkcs-7-padding-in-go-6da5d1d14590 | ||
4 | |||
5 | import "errors" | ||
6 | |||
7 | func Unpad(input []byte) ([]byte, error) { | ||
8 | if input == nil || len(input) == 0 { | ||
9 | return nil, nil | ||
10 | } | ||
11 | |||
12 | pc := input[len(input)-1] | ||
13 | pl := int(pc) | ||
14 | err := checkPaddingIsValid(input, pl) | ||
15 | if err != nil { | ||
16 | return nil, err | ||
17 | } | ||
18 | return input[:len(input)-pl], nil | ||
19 | } | ||
20 | |||
21 | func checkPaddingIsValid(input []byte, paddingLength int) error { | ||
22 | if len(input) < paddingLength { | ||
23 | return errors.New("invalid padding") | ||
24 | } | ||
25 | p := input[len(input)-(paddingLength):] | ||
26 | for _, pc := range p { | ||
27 | if uint(pc) != uint(len(p)) { | ||
28 | return errors.New("invalid padding") | ||
29 | } | ||
30 | } | ||
31 | return nil | ||
32 | } | ||
33 | |||
34 | func Pad(input []byte, blockSize int) []byte { | ||
35 | r := len(input) % blockSize | ||
36 | pl := blockSize - r | ||
37 | for i := 0; i < pl; i++ { | ||
38 | input = append(input, byte(pl)) | ||
39 | } | ||
40 | return input | ||
41 | } | ||