Retaining the padded bytes of Structural Padding in Python
Structural Padding means aligning the data into blocks of fixed size in order to ease the operations of particular Computer Architectures, Cryptographic algorithms accordingly. We pad(add enough bytes) the operational data (which is not necessarily structured) in order to serve the machine. Padded bytes may interrupt the original data, to identify the number of padded bytes, the following approach helps.
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:
# padding with 'white spaces' def pad(text, block_size): # Calculate the missing number of bytes pad_size = block_size - len (text) % block_size # Add missing bytes with 'white spaces' fit_text = text + ( " " * pad_size) return (fit_text) def main(): # text already contains 'white spaces' to # the Right, assumptions go wrong here block_size = 20 text = "HALL OF BYTES " print (pad(text, block_size)) main() |
Output :
'HALL OF BYTES '
Example 2:
Here is how to retain the padded number of bytes
# Python Program to retain padded bytes def pad(text, block_size): # Calculate the missing number of # bytes, say N pad_size = block_size - len (text) % block_size # Pad with character of N fit_text = text + chr (pad_size) * pad_size return (fit_text, ) def main(): text = "HALL OF BYTES" # structural unit of size 20 block_size = 20 print (pad(text, block_size)) # Driver Code main() |
Output :
'HALL OF BYTES\x07\x07\x07\x07\x07\x07\x07' # thus 7 bytes were padded.
# appropriate method to retain padded bytes def pad(text, block_size): # Calculate the missing number of # bytes, say N pad_size = block_size - len (text) % block_size # Pad with character of N fit_text = text + chr (pad_size) * pad_size return (fit_text, ) def main(): text = "PRECISELY RETAINED" # structural unit of size 20 block_size = 20 print (pad(text, block_size)) # Driver Code main() |
Output :
'PRECISELY RETAINED\x02\x02' # Thus two bytes were padded.