Skip to content

Instantly share code, notes, and snippets.

@MichaelAquilina
Created August 19, 2013 17:48
Show Gist options
  • Save MichaelAquilina/6271987 to your computer and use it in GitHub Desktop.
Save MichaelAquilina/6271987 to your computer and use it in GitHub Desktop.
PKCS7 Padding in python
def _pad(text, block_size):
"""
Performs padding on the given plaintext to ensure that it is a multiple
of the given block_size value in the parameter. Uses the PKCS7 standard
for performing padding.
"""
no_of_blocks = math.ceil(len(text)/float(block_size))
pad_value = int(no_of_blocks * block_size - len(text))
if pad_value == 0:
return text + chr(block_size) * block_size
else:
return text + chr(pad_value) * pad_value
@cono
Copy link

cono commented Mar 20, 2023

why just not use:

    pad_value = block_size - len(text) % block_size

    return text + chr(pad_value) * pad_value

@MichaelAquilina
Copy link
Author

@cono I'm afraid 10 years ago is far too long for me to remember why I did this :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment