Skip to content

Instantly share code, notes, and snippets.

@HoLyVieR
Forked from wangxiaodong/PKCS7Encoder
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HoLyVieR/4c6f11039db839406f09 to your computer and use it in GitHub Desktop.
Save HoLyVieR/4c6f11039db839406f09 to your computer and use it in GitHub Desktop.
PKCS7Encoder.py
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