Since you're working with strings, you can use ljust() to do the padding.

readBytes = f.read(self.chunksize)
if readBytes:
    readBytes = readBytes.ljust(self.chunksize, b'\0')
Answer from Jeff Mercado on Stack Overflow
🌐
Python
docs.python.org › 3 › library › struct.html
struct — Interpret bytes as packed binary data
It packs or unpacks data based on the platform and compiler on which the Python interpreter was built. The result of packing a given C struct includes pad bytes which maintain proper alignment for the C types involved; similarly, alignment is taken into account when unpacking.
Discussions

encryption - How can I pad a sequence of bytes in Python 3? - Stack Overflow
I'm trying to encrypt files like PDFs or executables, but I can't pad it. I try to read the file in this method: with('file', 'rb') as file_read: line = file_read.read(n) --> n multple of ... More on stackoverflow.com
🌐 stackoverflow.com
August 18, 2016
aes - Weird padding in Crypto.Util.Padding.pad() function in python - Cryptography Stack Exchange
I'm trying to pad some plaintext to be a multiple of 16 bytes to use it as input in AES ECB block cipher. More on crypto.stackexchange.com
🌐 crypto.stackexchange.com
Python3 bytearray padding
Hi, I’m trying to create a padded bytearray in Python3. Currently I have something like this: inputstuff = ('A' , b'ABCD'), ('B' , b'EFGH'), ('C' , b'IJKL'), ('D' , b'MNOP') ] BA = bytearray() for thing in inputstuf… More on unix.com
🌐 unix.com
0
0
July 31, 2010
aes - Is this how padding can work? - Cryptography Stack Exchange
To remove the padding, read the last byte, then move that many values back and truncate. In python it would look something like this: More on crypto.stackexchange.com
🌐 crypto.stackexchange.com
November 19, 2012
🌐
Medium
medium.com › pythons-gurus › how-padding-works-in-python-and-how-to-use-it-8c0020830f8d
How Padding Works in Python and How to Use It | Python’s Gurus
December 5, 2024 - PKCS#7 Padding: Appends bytes to make the total length a multiple of the block size. Zero Padding: Appends zeros to the data. ... block_size = 8 data = "Python" # Padding to block size padded_data = data + "\0" * (block_size - len(data) % ...
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to pad a python bytearray
5 Best Ways to Pad a Python Bytearray - Be on the Right Side of Change
February 24, 2024 - This code snippet initializes a bytearray with the word ‘hello’, sets a desired length to 8, and decides to pad with zero bytes. It then enters a loop that continues appending the padding byte until the bytearray reaches the desired length.
🌐
PyPI
pypi.org › project › Padding
Padding · PyPI
May 3, 2011 - Usually 8 or 16 bytes (string) mode - padding scheme one in (CMS, Bit, ZeroLen, Null, Space, Random) Return:(string) Decrypted string without padding II.
🌐
GeeksforGeeks
geeksforgeeks.org › python › retaining-the-padded-bytes-of-structural-padding-in-python
Retaining the padded bytes of Structural Padding in Python - GeeksforGeeks
July 10, 2020 - This is traditional Structural Padding with 'White Spaces' as padding entities, which will not help us extract the precise bytes of original data Example 1: Python3 ·
🌐
GitHub
github.com › keenlabs › KeenClient-Python › blob › master › keen › Padding.py
KeenClient-Python/keen/Padding.py at master · keenlabs/KeenClient-Python
(2,'ZeroLen') : 'Pad with zeroes except make the last byte equal to the number (length) of padding bytes', (3,'Null') : 'Pad with null bytes.
Author: keenlabs
Author: rajivvishwa
Find elsewhere
🌐
Python
docs.python.org › 3.1 › library › struct.html
7.3. struct — Interpret bytes as packed binary data — Python v3.1.5 documentation
February 8, 2021 - This module performs conversions between Python values and C structs represented as Python bytes objects. This can be used in handling binary data stored in files or from network connections, among other sources. It uses Format Strings as compact descriptions of the layout of the C structs ...
🌐
Python
python-list.python.narkive.com › HYMYyPPA › pad-binary-string-with-a-given-byte-value-python-3
pad binary string with a given byte value (python 3)
You don't need to write your own function, just use the relevant string and bytes methods. Use the ljust and rjust (left and right justify) methods: To add padding on the left, justify on the right, and vise versa: py> "Hello".ljust(20, "\x0f") 'Hello\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f' py> "Hello".rjust(20, "\x0f") '\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0fHello' (The default fill character is space.)
🌐
Unix.com
unix.com › applications › programming
Python3 bytearray padding - Programming - Unix Linux Community
July 31, 2010 - Hi, I'm trying to create a padded bytearray in Python3. Currently I have something like this: inputstuff = [ ('A' , b'ABCD'), ('B' , b'EFGH'), ('C' , b'IJKL'), ('D' , b'MNOP') ] BA = bytearray() for thing in inputstuff: BA.extend(thing[1]) print(BA.decode('latin1')) print(BA) for thing in BA: print(thing) This works and gives output like this: ABCDEFGHIJKLMNOP bytearray(b'ABCDEFGHIJKLMNOP') 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 Which is expected.
🌐
Real Python
realpython.com › python-bytes
Bytes Objects: Handling Binary Data in Python – Real Python
March 5, 2025 - The format specifier ("08b") ensures appropriate padding to maintain a consistent length for each byte. Lastly, you combine the resulting bit patterns into a single string with spaces separating them.
🌐
Better Stack
betterstack.com › community › questions › how-to-pad-string-with-zeroes-in-python
How do I pad a string with zeroes in Python? | Better Stack Community
February 3, 2023 - To convert a string to bytes in Python, you can use the bytes function. This function takes two arguments: the string to encode and the encoding to use. The default encoding is utf-8.
Top answer
1 of 2
5

You normally want to use a fully invertible padding scheme, i.e. a padding scheme with an associated unpadding scheme such that $unpad(pad(X)) = X$ for every $X$.

Assuming you only append data at the end, and don't do different things depending on the content of the message, this means that you always have to append something, even if the message is already of the right length.

In your scheme, in the case of a message which has already the length of a multiple of the block length, you'll have to append a full block ending with a 16 (assuming a 16-byte block cipher like AES). Your unpadding function then reads the last byte, and knows it has to strip off 16 bytes.

You shouldn't do any special-casing with a block of a certain structure only in the case of a full block appended.

But note that you should preferably use standardized schemes to help interoperability - for example PKCS#7-padding works just like your scheme, but with a bit different filling of the padded data. (This, just like your scheme, requires that the number of appended bytes is encodable in a byte, i.e. a block size of less than 256 bytes = 2048 bits. I'm not aware of any common block cipher with a larger block size, but you would need a different padding scheme in this case.)

2 of 2
3

It looks fine though you are better off sticking to established standards which already have parsers written. That way you don't have any problems.

To remove the padding, read the last byte, then move that many values back and truncate. In python it would look something like this:

p = decrypt(key, ciphertext)
pad_len = p[len(p)-1]
return p[0:len(p)-pad_len]

🌐
Python
bugs.python.org › issue26746
Issue 26746: struct.pack(): trailing padding bytes on x64 - Python tracker
April 13, 2016 - This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/70933
🌐
Reddit
reddit.com › r/learnpython › padding a bin file
r/learnpython on Reddit: Padding a bin file
October 24, 2022 -

So I have a .bin file I am attempting to pad. I have two ranges I need to fill with 0xFF. I currently have it working with seek() and its writing bytes correctly to that one specific memory location but i need to do it for certain ranges in the file. Any pointers to the right direction would be much appreciated! I've provided what I have code wise so far.

Edit: After digging some more im wondering if i could put the seek in a for loop with the offset parameter as a counter variable, write the bytes to that offset and then increment the counter.

import os, re

path = "C:\\Users\\comp\\Desktop\\python padding"
os.chdir( path )
files = os.listdir( path )

for filename in files:
    if re.match('.*\.bin', filename):
        fh = open(filename, 'r+b')
        fh.seek(0x37fff)
        fh.write(bytes([0xff]))
        fh.close()
        name, ext = os.path.splitext(filename)
        os.rename(filename, name + "padded.bin")
🌐
GitHub
github.com › micropython › micropython-lib › issues › 145
Struct unpacking and pad bytes · Issue #145 · micropython/micropython-lib
January 16, 2017 - In CPython, when unpacking structs with pad bytes the pad bytes generate no output. Example: Python 3.4.2 (default, Oct 8 2014, 10:45:20) [GCC 4.9.1] on linux Type "help", "copyright", "credits" or "license" for more information. >>> imp...
Author: micropython