Reading Files as Binary Streams and Converting to Hexadecimal
def process_binary_file():
with open('./flag.zip', 'rb') as binary_data:
hex_content = binary_data.read().hex()
print(hex_content)
save_hex_data(hex_content)
def save_hex_data(content):
with open('output.txt', 'w') as output_file:
output_file.write(content)
if __name__ == '__main__':
process_binary_file()
Converting Binary Data to Base64 Encoding
import base64
def encode_to_base64():
with open('./flag.zip', 'rb') as source_file:
encoded_data = base64.b64encode(source_file.read())
print(encoded_data)
if __name__ == '__main__':
encode_to_base64()
Converting Hexadecimal Strings Back to Binary Files
import struct
def hex_to_binary():
with open("hex_data.txt", "r") as input_file:
hex_string = input_file.read().strip()
byte_pairs = [hex_string[i:i+2] for i in range(0, len(hex_string), 2)]
with open("reconstructed.bin", "wb") as output_file:
for pair in byte_pairs:
byte_value = struct.pack('B', int(pair, 16))
output_file.write(byte_value)
hex_to_binary()
Using binascii for Hexadecimal Cnoversions
The binascii module provides functions for converting between binary and hexadecimal representations:
>>> import binascii
>>> data = b'message{Secret_Data_Here}'
>>> binascii.b2a_hex(data)
b'6d6573736167657b5365637265745f446174615f486572657d'
>>> binascii.hexlify(data)
b'6d6573736167657b5365637265745f446174615f486572657d'
Converting heaxdecimal back to binary data:
>>> import binascii
>>> hex_data = '6d6573736167657b5365637265745f446174615f486572657d'
>>> binascii.a2b_hex(hex_data)
b'message{Secret_Data_Here}'
>>> binascii.unhexlify(hex_data)
b'message{Secret_Data_Here}'
Complete example for hex to binary conversion using binascii:
import binascii
def convert_hex_to_binary():
with open('./input.hex', 'r') as hex_file:
with open('output.bin', 'wb') as binary_file:
binary_file.write(binascii.unhexlify(hex_file.read().strip()))
convert_hex_to_binary()
Handling Base64 Encoded Images
For base64 encoded image data, you can embed it directly in HTML using the data URI scheme:
data:image/png;base64,your_base64_string_here