How to Encrypt a File in C# and Decrypt it
Encrypting a file in C# involves using cryptographic algorithms to convert the file’s contents into an unreadable format that can only be deciphered with the appropriate decryption key. Here’s a basic example of how to encrypt a file in C# using the AesManaged class, which is a symmetric encryption algorithm:
using System;
using System.IO;
using System.Security.Cryptography;
class FileEncryption
{
public static void EncryptFile(string inputFile, string outputFile, string password)
{
using (AesManaged aesAlg = new AesManaged())
{
// Set the encryption key and initialization vector (IV) from the password
byte[] key = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(“SaltValue”)).GetBytes(32);
byte[] iv = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(“SaltValue”)).GetBytes(16);
// Create an encryptor to perform the stream transform
ICryptoTransform encryptor = aesAlg.CreateEncryptor(key, iv);
using (FileStream inputFileStream = new FileStream(inputFile, FileMode.Open))
using (FileStream outputFileStream = new FileStream(outputFile, FileMode.Create))
using (CryptoStream cryptoStream = new CryptoStream(outputFileStream, encryptor, CryptoStreamMode.Write))
{
int data;
while ((data = inputFileStream.ReadByte()) != -1)
{
cryptoStream.WriteByte((byte)data);
}
}
}
}
public static void Main(string[] args)
{
string inputFile = “input.txt”;
string outputFile = “encrypted.bin”;
string password = “YourSuperSecretPassword”;
EncryptFile(inputFile, outputFile, password);
Console.WriteLine(“File encrypted successfully.”);
}
}
In this example:
- We use the AesManaged class for symmetric encryption. It’s essential to derive encryption keys and IV from a password, and you should use a strong password.
- We create an encryptor using the derived key and IV.
- We open the input and output file streams and use a CryptoStream to encrypt the data from the input file and write it to the output file.
- Make sure to replace
"input.txt"
,"encrypted.bin"
, and"YourSuperSecretPassword"
with your actual file paths and password.
Remember to handle exceptions and use secure key management practices when implementing encryption in a real application. Additionally, consider using other encryption methods, such as RSA for asymmetric encryption, depending on your specific use case and security requirements.