-
-
Save HoLyVieR/4c6f11039db839406f09 to your computer and use it in GitHub Desktop.
PKCS7Encoder.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PKCS7Encoder(): | |
""" | |
Technique for padding a string as defined in RFC 2315, section 10.3, | |
note #2 | |
""" | |
class InvalidBlockSizeError(Exception): | |
"""Raised for invalid block sizes""" | |
pass | |
def __init__(self, block_size=16): | |
if block_size < 1 or block_size > 99: | |
raise InvalidBlockSizeError('The block size must be between 1 ' \ | |
'and 99') | |
self.block_size = block_size | |
def encode(self, text): | |
text_length = len(text) | |
amount_to_pad = self.block_size - (text_length % self.block_size) | |
if amount_to_pad == 0: | |
amount_to_pad = self.block_size | |
pad = unhexlify('%02x' % amount_to_pad) | |
return text + pad * amount_to_pad | |
def decode(self, text): | |
pad = int(hexlify(text[-1]), 16) | |
if not text[-pad:] == chr(pad) * pad: | |
raise Exception("Invalid padding") | |
return text[:-pad] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment