Debian Codegraph @

pad/pad.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 implements some padding schemes
5 // for block ciphers.
6 package pad
7
8 import (
9 cryptorand "crypto/rand"
10 "errors"
11 "io"
12 )
13
14 var badPadErr = errors.New("bad padding bytes")
15 var notMulOfBlockErr = errors.New("src is not a multiply of the padding blocksize")
16
17 // The Padding interface represents a padding scheme.
18 type Padding interface {
19
20 // BlockSize returns the block size of the padding.
21 BlockSize() int
22
23 // Returns the overhead, the padding will cause
24 // by padding the given byte slice. The overhead
25 // will always be between 1 and BlockSize() inclusively.
26 Overhead(src []byte) int
27
28 // Pads the last (may incomplete) block of the src slice
29 // to a padded and complete block, appends the padding bytes
30 // to the src slice and returns this slice.
31 // The length of the returned slice is len(src) + Overhead(src)
32 Pad(src []byte) []byte
33
34 // Takes a slice and tries to remove the padding bytes
35 // form the last block. Therefore the length of the
36 // src argument must be a multiply of the blocksize.
37 // If the returned error is nil, the padding could be
38 // removed successfully. The returned slice holds the
39 // unpadded src bytes.
40 Unpad(src []byte) ([]byte, error)
41 }
42
43 // NewX923 returns a new pad.Padding implementing the ANSI X.923 scheme.
44 // Only block sizes between 1 and 255 are valid.
45 func NewX923(blocksize int) Padding {
46 if blocksize < 1 || blocksize > 255 {
47 panic("illegal blocksize - size must between 0 and 256")
48 }
49 pad := x923Padding(blocksize)
50 return pad
51 }
52
53 // NewPKCS7 returns a new pad.Padding implementing the PKCS 7 scheme.
54 // Only block sizes between 1 and 255 are valid.
55 func NewPKCS7(blocksize int) Padding {
56 if blocksize < 1 || blocksize > 255 {
57 panic("illegal blocksize - size must between 0 and 256")
58 }
59 pad := pkcs7Padding(blocksize)
60 return pad
61 }
62
63 // NewISO10126 returns a new pad.Padding, which uses the padding scheme
64 // described in ISO 10126. The padding bytes are taken
65 // form the given rand argument. If rand is nil, crypto/rand will be used.
66 // Only block sizes between 1 and 255 are valid.
67 func NewISO10126(blocksize int, rand io.Reader) Padding {
68 if blocksize < 1 || blocksize > 255 {
69 panic("illegal blocksize - size must between 0 and 256")
70 }
71 pad := new(isoPadding)
72 pad.blocksize = blocksize
73 if rand == nil {
74 pad.random = cryptorand.Reader
75 } else {
76 pad.random = rand
77 }
78 return pad
79 }
80
81 // Returns the overhead for a given slice with a
82 // specific block size.
83 func overhead(blocksize int, src []byte) int {
84 return blocksize - (len(src) % blocksize)
85 }