Exercise
BMP File Encryption
Objective
Develop a Python program to encrypt or decrypt a BMP image file by swapping the "BM" signature in the first two bytes with "MB" and vice versa.
Utilize the advanced FileStream constructor to allow reading and writing at the same time.
Example Python Exercise
Show Python Code
# Python program to encrypt or decrypt a BMP file by swapping the "BM" signature
def encrypt_decrypt_bmp(filename):
try:
# Open the BMP file in binary read and write mode
with open(filename, 'r+b') as file:
# Read the first two bytes (the signature)
signature = file.read(2)
# Check if the signature is "BM"
if signature == b'BM':
print("Encrypting: Swapping 'BM' to 'MB'...")
# Move the file pointer back to the start
file.seek(0)
# Write "MB" to replace "BM"
file.write(b'MB')
elif signature == b'MB':
print("Decrypting: Swapping 'MB' to 'BM'...")
# Move the file pointer back to the start
file.seek(0)
# Write "BM" to replace "MB"
file.write(b'BM')
else:
print(f"Error: The file '{filename}' does not have a valid BMP signature.")
except FileNotFoundError:
print(f"Error: The file '{filename}' does not exist.")
except Exception as e:
print(f"Error: {str(e)}")
# Example usage
encrypt_decrypt_bmp("example.bmp")
Output
Encrypting: Swapping 'BM' to 'MB'...
Share this Python Exercise
More Python Programming Exercises of Managing Files
Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.
In this exercise, you will develop a Python program to read a CSV file containing comma-separated values. This exercise is perfect for practicing file handling...
In this exercise, you will develop a Python program to compare two files (of any type) and determine if they are identical (i.e., have the same content). This exer...
In this exercise, you will develop a Python program to decode and display a Netpbm image file. This exercise is perfect for practicing file handling, string ma...
In this exercise, you will develop a Python program to extract only the alphabetic characters contained in a binary file and dump them into a separate file. This e...
In this exercise, you will develop a Python program to create a "dump" utility: a hex viewer that displays the contents of a file, with 16 bytes in each row and 24 ro...
In this exercise, you will develop a Python program to create a utility that censors text files. This exercise is perfect for practicing file handling, string ...