1#
2# Util/Padding.py : Functions to manage padding
3#
4# ===================================================================
5#
6# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
7# All rights reserved.
8#
9# Redistribution and use in source and binary forms, with or without
10# modification, are permitted provided that the following conditions
11# are met:
12#
13# 1. Redistributions of source code must retain the above copyright
14# notice, this list of conditions and the following disclaimer.
15# 2. Redistributions in binary form must reproduce the above copyright
16# notice, this list of conditions and the following disclaimer in
17# the documentation and/or other materials provided with the
18# distribution.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31# POSSIBILITY OF SUCH DAMAGE.
32# ===================================================================
33
34__all__ = [ 'pad', 'unpad' ]
35
36from Crypto.Util.py3compat import *
37
38
39def pad(data_to_pad, block_size, style='pkcs7'):
40 """Apply standard padding.
41
42 Args:
43 data_to_pad (byte string):
44 The data that needs to be padded.
45 block_size (integer):
46 The block boundary to use for padding. The output length is guaranteed
47 to be a multiple of :data:`block_size`.
48 style (string):
49 Padding algorithm. It can be *'pkcs7'* (default), *'iso7816'* or *'x923'*.
50
51 Return:
52 byte string : the original data with the appropriate padding added at the end.
53 """
54
55 padding_len = block_size - len(data_to_pad) % block_size
56
57 if style == 'pkcs7':
58 padding = bchr(padding_len) * padding_len
59 elif style == 'x923':
60 padding = bchr(0)*(padding_len-1) + bchr(padding_len)
61 elif style == 'iso7816':
62 padding = bchr(128) + bchr(0) * (padding_len-1)
63 else:
64 raise ValueError("Unknown padding style")
65
66 return data_to_pad + padding
67
68
69def unpad(padded_data, block_size, style='pkcs7'):
70 """Remove standard padding.
71
72 Args:
73 padded_data (byte string):
74 A piece of data with padding that needs to be stripped.
75 block_size (integer):
76 The block boundary to use for padding. The input length
77 must be a multiple of :data:`block_size`.
78 style (string):
79 Padding algorithm. It can be *'pkcs7'* (default), *'iso7816'* or *'x923'*.
80 Return:
81 byte string : data without padding.
82 Raises:
83 ValueError: if the padding is incorrect.
84 """
85
86 pdata_len = len(padded_data)
87
88 if pdata_len == 0:
89 raise ValueError("Zero-length input cannot be unpadded")
90
91 if pdata_len % block_size:
92 raise ValueError("Input data is not padded")
93
94 if style in ('pkcs7', 'x923'):
95 padding_len = bord(padded_data[-1])
96
97 if padding_len < 1 or padding_len > min(block_size, pdata_len):
98 raise ValueError("Padding is incorrect.")
99
100 if style == 'pkcs7':
101 if padded_data[-padding_len:] != bchr(padding_len)*padding_len:
102 raise ValueError("PKCS#7 padding is incorrect.")
103 else:
104 if padded_data[-padding_len:-1] != bchr(0)*(padding_len-1):
105 raise ValueError("ANSI X.923 padding is incorrect.")
106
107 elif style == 'iso7816':
108 padding_len = pdata_len - padded_data.rfind(bchr(128))
109
110 if padding_len < 1 or padding_len > min(block_size, pdata_len):
111 raise ValueError("Padding is incorrect.")
112
113 if padding_len > 1 and padded_data[1-padding_len:] != bchr(0)*(padding_len-1):
114 raise ValueError("ISO 7816-4 padding is incorrect.")
115 else:
116 raise ValueError("Unknown padding style")
117
118 return padded_data[:-padding_len]
119