【问题标题】:Do i need to call the class "File Stream" to encrypt the data in a file?我是否需要调用“文件流”类来加密文件中的数据?
【发布时间】:2021-10-10 22:39:47
【问题描述】:

我编写了一个程序,它遍历一个目录,找到具有特定扩展名的文件,然后对其进行加密。虽然它没有加密实际文件,但它正在加密文件目录。 它是一个控制台应用程序,显示加密消息和解密消息。 这是代码的核心部分

static void Main(string[] args)
{
    string root = @"C:\Users\Owner\Documents";
    var files = from file in Directory.EnumerateFiles(root) select file;
    foreach (var file in files)
    {
        if (file.EndsWith(".txt"))
        {
            try
            {
                // Create Aes that generates a new key and initialization vector (IV).    
                // Same key must be used in encryption and decryption    
                using (AesManaged aes = new AesManaged())
                {
                    // Encrypt string    
                    byte[] encrypted = Encrypt(file, aes.Key, aes.IV);
                    // Print encrypted string    
                    Console.WriteLine($"Encrypted data: {System.Text.Encoding.UTF8.GetString(encrypted)}");
                    // Decrypt the bytes to a string.    
                    string decrypted = Decrypt(encrypted, aes.Key, aes.IV);
                    // Print decrypted string. It should be same as raw data    
                    Console.WriteLine($"Decrypted data: {decrypted}");
                }
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.Message);
            }
            Console.ReadKey();
        }

输出:

加密数据:?U↔C?♣#Y?f"?8?a?*????♦????&?,¶?

解密数据:C:\Users\Owner\Documents\script.txt

我进入文件,里面没有加密

【问题讨论】:

  • 您没有在任何地方写入加密数据。
  • @mjwills:他当然是。到控制台:-)

标签: c# encryption aes filestream


【解决方案1】:

让我们看看这些行

byte[] encrypted = Encrypt(file, aes.Key, aes.IV);

这会加密文件的名称,而不是文件的内容。要加密内容,您可以将其替换为

byte[] encrypted = Encrypt(File.ReadAllText(file), aes.Key, aes.IV);

现在我们来看看

// Print encrypted string    
Console.WriteLine($"Encrypted data {System.Text.Encoding.UTF8.GetString(encrypted)}");

这部分很好。它将加密内容写入控制台(仅)。如果您想将其写回原始文件(从而加密文件),您可以改为或另外执行

File.WriteAllText(file, Encoding.UTF8.GetString(encrypted));

解密同理,需要读取加密文件的内容,将解密后的内容写回文件中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多