-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPKCS7.py
40 lines (34 loc) · 1.16 KB
/
PKCS7.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# Reference https://gist.github.com/chrix2/4171336
import binascii
import StringIO
class PKCS7Encoder(object):
def __init__(self, k=16):
self.k = k
## @param text The padded text for which the padding is to be removed.
# @exception ValueError Raised when the input padding is missing or corrupt.
def decode(self, text):
'''
Remove the PKCS#7 padding from a text string
'''
nl = len(text)
val = int(binascii.hexlify(text[-1]), 16)
if val > self.k:
raise ValueError('Input is not padded or padding is corrupt')
l = nl - val
return text[:l]
## @param text The text to encode.
def encode(self, text):
'''
Pad an input string according to PKCS#7
'''
l = len(text)
output = StringIO.StringIO()
val = self.k - (l % self.k)
for _ in xrange(val):
output.write('%02x' % val)
return text + binascii.unhexlify(output.getvalue())
if __name__ == '__main__':
encoder = PKCS7Encoder()
padded_value = encoder.encode('thismessage')
print padded_value.encode('hex')
print encoder.decode(padded_value)