Debian Codegraph @

padding/padding.go

raw symbols SCIP
1 // Package padding adds and removes padding for AES-CBC mode.
2 //
3 // Copyright (c) 2013 CloudFlare, Inc.
4
5 package padding
6
7 import "errors"
8
9 // The final byte of a padded []byte indicates the number of padding
10 // bytes that were added. The padding bytes are always NUL bytes and
11 // up to 16 bytes may be added.
12 //
13 // Examples:
14 //
15 // 1. Data to be padded has a length divisible by 16. 16 bytes will be
16 // added where the first 15 are 0x00 and the final byte is 0x10.
17 //
18 // 2. Data to be padded has a length with remainder 15 when divided by
19 // 16. One byte will be added and that byte will be 0x01 (indicating
20 // one byte of padding).
21 //
22 // 3. Data to be padded has a length with remainder 2 when divided by
23 // 16. 14 bytes will be added. The first 13 will be 0x00 and then final
24 // byte will be 0x0e.
25 //
26 // Removing padding is trivial: the number of bytes specified by the
27 // final byte are removed.
28
29 // RemovePadding removes padding from data that was added with
30 // AddPadding
31 func RemovePadding(b []byte) ([]byte, error) {
32 l := int(b[len(b)-1])
33 if l > 16 {
34 return nil, errors.New("Padding incorrect")
35 }
36
37 return b[:len(b)-l], nil
38 }
39
40 // AddPadding adds padding to a block of data
41 func AddPadding(b []byte) []byte {
42 l := 16 - len(b)%16
43 padding := make([]byte, l)
44 padding[l-1] = byte(l)
45 return append(b, padding...)
46 }