Debian Codegraph @

pad/pkcs7.go

raw symbols SCIP
1 // Use of this source code is governed by a license
2 // that can be found in the LICENSE file.
3
4 package pad
5
6 type pkcs7Padding int
7
8 func (p pkcs7Padding) BlockSize() int {
9 return int(p)
10 }
11
12 func (p pkcs7Padding) Overhead(src []byte) int {
13 return overhead(p.BlockSize(), src)
14 }
15
16 func (p pkcs7Padding) Pad(src []byte) []byte {
17 overhead := p.Overhead(src)
18
19 dst := make([]byte, overhead)
20 for i := range dst {
21 dst[i] = byte(overhead)
22 }
23 return append(src, dst...)
24 }
25
26 func (p pkcs7Padding) Unpad(src []byte) ([]byte, error) {
27 length := len(src)
28 if length == 0 || length%p.BlockSize() != 0 {
29 return nil, notMulOfBlockErr
30 }
31
32 block := src[(length - p.BlockSize()):]
33 unLen, err := verifyPkcs7(block, p.BlockSize())
34 if err != nil {
35 return nil, err
36 }
37 return src[:(length - p.BlockSize() + unLen)], nil
38 }
39
40 // Verify the PKCS7 padding - NOTICE: not constant time!
41 func verifyPkcs7(block []byte, blocksize int) (p int, err error) {
42 padLen := block[blocksize-1]
43 if padLen == 0 || int(padLen) > blocksize {
44 err = badPadErr
45 return
46 }
47
48 p = blocksize - int(padLen)
49 for _, b := range block[p:] {
50 if b != padLen {
51 err = badPadErr
52 }
53 }
54 return
55 }