diff options
author | Mike Crute <mike@crute.us> | 2023-10-24 22:19:22 -0700 |
---|---|---|
committer | Mike Crute <mike@crute.us> | 2023-10-24 22:19:22 -0700 |
commit | 9d5f99a5b4f86e5a880296c0d52d55848791871a (patch) | |
tree | fbfe39ed90185052e3499c549d9365d3a4a2259b | |
parent | 72bf9d0a62c8459ce7c832298c723656e7e6d384 (diff) | |
download | golib-9d5f99a5b4f86e5a880296c0d52d55848791871a.tar.bz2 golib-9d5f99a5b4f86e5a880296c0d52d55848791871a.tar.xz golib-9d5f99a5b4f86e5a880296c0d52d55848791871a.zip |
crypto: add pkcs7v0.8.1
-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 | } | ||