Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Security.Cryptography;
- using System.Threading.Tasks;
- namespace FileEncryption
- {
- class Program
- {
- static void Main(string[] args)
- {
- string inputDirectoryPath = "path/to/input/directory";
- string outputDirectoryPath = "path/to/output/directory";
- string password = "mysecret";
- EncryptDirectory(inputDirectoryPath, outputDirectoryPath, password);
- }
- static void EncryptDirectory(string inputDirectoryPath, string outputDirectoryPath, string password)
- {
- // Get all files in the input directory
- string[] inputFilePaths = Directory.GetFiles(inputDirectoryPath);
- // Create the output directory if it doesn't exist
- if (!Directory.Exists(outputDirectoryPath))
- {
- Directory.CreateDirectory(outputDirectoryPath);
- }
- // Create an array of tasks to encrypt each file in parallel
- Task[] tasks = new Task[inputFilePaths.Length];
- for (int i = 0; i < inputFilePaths.Length; i++)
- {
- string inputFilePath = inputFilePaths[i];
- string outputFilePath = Path.Combine(outputDirectoryPath, Path.GetFileName(inputFilePath));
- tasks[i] = Task.Run(() => EncryptFile(inputFilePath, outputFilePath, password));
- }
- // Wait for all tasks to complete
- Task.WaitAll(tasks);
- }
- static void EncryptFile(string inputFilePath, string outputFilePath, string password)
- {
- using (FileStream inputStream = File.OpenRead(inputFilePath))
- using (FileStream outputStream = File.OpenWrite(outputFilePath))
- using (Aes aes = Aes.Create())
- {
- aes.KeySize = 256;
- aes.BlockSize = 128;
- aes.Mode = CipherMode.CBC;
- aes.Padding = PaddingMode.PKCS7;
- byte[] salt = new byte[16];
- using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
- {
- rng.GetBytes(salt);
- }
- aes.GenerateIV();
- byte[] key = new Rfc2898DeriveBytes(password, salt, 10000).GetBytes(32);
- outputStream.Write(salt, 0, salt.Length);
- outputStream.Write(aes.IV, 0, aes.IV.Length);
- using (CryptoStream cryptoStream = new CryptoStream(outputStream, aes.CreateEncryptor(key, aes.IV), CryptoStreamMode.Write))
- {
- inputStream.CopyTo(cryptoStream);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement