溫馨提示×

c#怎么加密文件夾

c#
小億
158
2024-10-27 00:33:37
欄目: 編程語言

在C#中,可以使用System.IO.Directory類來遍歷文件夾,并使用System.IO.File類來讀取和寫入文件。為了加密文件夾,可以選擇使用對稱加密算法(如AES)或非對稱加密算法(如RSA)。

以下是一個使用AES加密文件夾的示例代碼:

  1. 首先,需要生成一個密鑰和一個初始化向量(IV),并將它們保存到文件中??梢允褂?code>System.Security.Cryptography命名空間中的類來實現這一點。
using System.Security.Cryptography;
using System.IO;

// 生成密鑰和IV
byte[] key = new byte[32]; // AES密鑰長度為32字節
byte[] iv = new byte[16]; // AES IV長度為16字節
using (Aes aes = Aes.Create())
{
    aes.Key = key;
    aes.IV = iv;

    // 保存密鑰和IV到文件中
    using (FileStream fs = new FileStream("key.bin", FileMode.Create))
    {
        aes.SaveKey(fs);
    }

    using (FileStream fs = new FileStream("iv.bin", FileMode.Create))
    {
        fs.Write(iv, 0, iv.Length);
    }
}
  1. 接下來,需要遍歷文件夾中的所有文件,并將它們加密??梢允褂眠f歸方法來實現這一點。
using System.IO;

// 加密文件夾中的文件
void EncryptFilesInFolder(string folderPath)
{
    DirectoryInfo di = new DirectoryInfo(folderPath);
    FileInfo[] fis = di.GetFiles();

    foreach (FileInfo fi in fis)
    {
        string filePath = fi.FullName;
        string encryptedFilePath = Path.Combine(folderPath, "encrypted_" + fi.Name);

        // 加密文件
        EncryptFile(filePath, encryptedFilePath);
    }

    DirectoryInfo[] dis = di.GetDirectories();

    foreach (DirectoryInfo di in dis)
    {
        string folderPath = di.FullName;
        string encryptedFolderPath = Path.Combine(folderPath, "encrypted_" + di.Name);

        // 遞歸加密子文件夾
        EncryptFilesInFolder(folderPath);
    }
}

// 加密單個文件
void EncryptFile(string inputFilePath, string outputFilePath)
{
    using (Aes aes = Aes.Create())
    {
        aes.Key = File.ReadAllBytes("key.bin");
        aes.IV = File.ReadAllBytes("iv.bin");

        using (ICryptoTransform encryptor = aes.CreateEncryptor())
        {
            using (FileStream fs = new FileStream(inputFilePath, FileMode.Open))
            {
                using (CryptoStream cs = new CryptoStream(fs, encryptor, CryptoStreamMode.Read))
                {
                    using (FileStream fsOut = new FileStream(outputFilePath, FileMode.Create))
                    {
                        cs.CopyTo(fsOut);
                    }
                }
            }
        }
    }
}
  1. 最后,可以調用EncryptFilesInFolder方法來加密整個文件夾。
string folderPath = @"C:\path\to\folder";
EncryptFilesInFolder(folderPath);

請注意,這只是一個簡單的示例,實際應用中可能需要考慮更多的因素,如錯誤處理、異常處理、密鑰和IV的管理等。此外,加密后的文件將無法直接讀取,需要使用相應的解密算法進行解密。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女