BMP File Encryption - Python Programming Exercise

In this exercise, you will 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. This exercise is perfect for practicing file handling, byte manipulation, and encryption techniques in Python. By implementing this program, you will gain hands-on experience in handling file operations, byte manipulation, and encryption techniques in Python. This exercise not only reinforces your understanding of file handling but also helps you develop efficient coding practices for managing user interactions.

 Category

Managing Files

 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

 Copy 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.

  •  CSV Data Converter

    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...

  •  File content comparer

    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...

  •  Show BMP on console

    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...

  •  Extract Text Information from a Binary File

    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...

  •  Dump

    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...

  •  Text Filter

    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 ...