I’m implementing PKCS#7 padding right now in Python and need to pad chunks of my file in order to amount to a number divisible by sixteen. I’ve been recommended to use the following method to append these bytes:
input_chunk += '\x00'*(-len(input_chunk)%16)
What I need to do is the following:
input_chunk_remainder = len(input_chunk) % 16
input_chunk += input_chunk_remainder * input_chunk_remainder
Obviously, the second line above is wrong; I need to convert the first input_chunk_remainder to a single byte string. How can I do this in Python?
In Python 3, you can create bytes of a given numeric value with the
bytes()type; you can pass in a list of integers (between 0 and 255):An alternative method is to use an
array.array()with the right number of integers:or use the
struct.pack()function to pack your integers into bytes:There may be more ways.. 🙂
In Python 2 (ancient now), you can do the same by using the
chr()function: