Programa Para 'Cifrar-Descifrar' Archivos De Imagen BMP En C#

Este programa permite cifrar y descifrar archivos de imagen BMP manipulando la marca "BM" ubicada en los dos primeros bytes del archivo. El programa cambia la marca "BM" al principio del archivo por "MB" para el cifrado e invierte el proceso para el descifrado. El cifrado y el descifrado se realizan mediante el constructor avanzado FileStream, que permite la lectura y escritura simultáneas. Esto garantiza que el programa pueda modificar el archivo en el momento sin necesidad de una copia temporal. El objetivo principal de este programa es demostrar la manipulación sencilla de archivos y cómo la clase FileStream puede utilizarse tanto para leer como para escribir en el mismo archivo.

Grupo

Manejo de archivos en C#

Objectivo

1. El programa requiere que el usuario proporcione el nombre del archivo BMP que se va a cifrar o descifrar.
2. Lee los dos primeros bytes del archivo para identificar si empieza por "BM" o "MB".
3. Si los dos primeros bytes son "BM", el programa los reemplazará por "MB" (cifrado).
4. Si los dos primeros bytes son "MB", el programa los reemplazará por "BM" (descifrado).
5. Utilice el programa de la siguiente manera:

encryptDecrypt myImage.bmp

6. El programa modifica el archivo en su lugar y no crea uno nuevo.

Cree un programa para cifrar/descifrar un archivo de imagen BMP cambiando la marca "BM" en los dos primeros bytes a "MB" y viceversa.
Utilice el constructor avanzado FileStream para habilitar la lectura y escritura simultáneas.

Ejemplo de ejercicio en C#

 Copiar código C#
using System;
using System.IO;

class BMPEncryptDecrypt
{
    // Main method where the program starts execution
    static void Main(string[] args)
    {
        // Check if the user provided the correct number of arguments
        if (args.Length != 1)
        {
            Console.WriteLine("Usage: encryptDecrypt ");
            return;
        }

        // Get the input BMP file name from the arguments
        string fileName = args[0];

        // Check if the specified file exists
        if (!File.Exists(fileName))
        {
            Console.WriteLine("The specified file does not exist.");
            return;
        }

        try
        {
            // Open the file with FileStream for both reading and writing
            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
            {
                // Read the first two bytes of the file to check the "BM" marker
                byte[] buffer = new byte[2];
                fs.Read(buffer, 0, 2);

                // Check if the first two bytes are "BM" or "MB"
                if (buffer[0] == 'B' && buffer[1] == 'M')
                {
                    // If it's "BM", change it to "MB" (encryption)
                    Console.WriteLine("Encrypting file...");

                    // Move the file pointer back to the start of the file
                    fs.Seek(0, SeekOrigin.Begin);

                    // Write "MB" instead of "BM"
                    fs.WriteByte((byte)'M'); // Write 'M'
                    fs.WriteByte((byte)'B'); // Write 'B'

                    Console.WriteLine("File encrypted successfully.");
                }
                else if (buffer[0] == 'M' && buffer[1] == 'B')
                {
                    // If it's "MB", change it to "BM" (decryption)
                    Console.WriteLine("Decrypting file...");

                    // Move the file pointer back to the start of the file
                    fs.Seek(0, SeekOrigin.Begin);

                    // Write "BM" instead of "MB"
                    fs.WriteByte((byte)'B'); // Write 'B'
                    fs.WriteByte((byte)'M'); // Write 'M'

                    Console.WriteLine("File decrypted successfully.");
                }
                else
                {
                    // If the first two bytes are not "BM" or "MB", print an error
                    Console.WriteLine("The file does not have the expected 'BM' or 'MB' marker.");
                }
            }
        }
        catch (Exception ex)
        {
            // Handle any exceptions that may occur during file processing
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

 Output

//For example, if you run the program on a BMP file named myImage.bmp:

//When encrypting (changing "BM" to "MB"):
Encrypting file...
File encrypted successfully.

//When decrypting (changing "MB" back to "BM"):
Decrypting file...
File decrypted successfully.

Comparte este ejercicio de C#