加密/解密大文件 (.NET)

2023-12-24

我必须加密、存储然后解密大文件。最好的方法是什么?我听说 RSA 加密很昂贵,建议使用 RSA 加密 AES 密钥,然后使用 AES 密钥加密大文件。任何带有示例的建议都会很棒。


一种有机体很大,另一种有机体很小,尽管我们看到它时都知道它很昂贵。眨眼眨眼。

尝试在您的环境中对类似以下内容进行基准测试,看看您处于什么位置:

编辑 2/13/2012:代码已经更新,因为我变得(不知不觉地)变得更聪明,并且还注意到一些悄悄出现的剪切粘贴错误。我很抱歉。

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

...

    // Rfc2898DeriveBytes constants:
    public readonly byte[] salt = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // Must be at least eight bytes.  MAKE THIS SALTIER!
    public const int iterations = 1042; // Recommendation is >= 1000.

    /// <summary>Decrypt a file.</summary>
    /// <remarks>NB: "Padding is invalid and cannot be removed." is the Universal CryptoServices error.  Make sure the password, salt and iterations are correct before getting nervous.</remarks>
    /// <param name="sourceFilename">The full path and name of the file to be decrypted.</param>
    /// <param name="destinationFilename">The full path and name of the file to be output.</param>
    /// <param name="password">The password for the decryption.</param>
    /// <param name="salt">The salt to be applied to the password.</param>
    /// <param name="iterations">The number of iterations Rfc2898DeriveBytes should use before generating the key and initialization vector for the decryption.</param>
    public void DecryptFile(string sourceFilename, string destinationFilename, string password, byte[] salt, int iterations)
    {
        AesManaged aes = new AesManaged();
        aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
        aes.KeySize = aes.LegalKeySizes[0].MaxSize;
        // NB: Rfc2898DeriveBytes initialization and subsequent calls to   GetBytes   must be eactly the same, including order, on both the encryption and decryption sides.
        Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);
        aes.Key = key.GetBytes(aes.KeySize / 8);
        aes.IV = key.GetBytes(aes.BlockSize / 8);
        aes.Mode = CipherMode.CBC;
        ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV);

        using (FileStream destination = new FileStream(destinationFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None))
        {
            using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
            {
                try
                {
                    using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        source.CopyTo(cryptoStream);
                    }
                }
                catch (CryptographicException exception)
                {
                    if (exception.Message == "Padding is invalid and cannot be removed.")
                        throw new ApplicationException("Universal Microsoft Cryptographic Exception (Not to be believed!)", exception);
                    else
                        throw;
                }
            }
        }
    }

    /// <summary>Encrypt a file.</summary>
    /// <param name="sourceFilename">The full path and name of the file to be encrypted.</param>
    /// <param name="destinationFilename">The full path and name of the file to be output.</param>
    /// <param name="password">The password for the encryption.</param>
    /// <param name="salt">The salt to be applied to the password.</param>
    /// <param name="iterations">The number of iterations Rfc2898DeriveBytes should use before generating the key and initialization vector for the decryption.</param>
    public void EncryptFile(string sourceFilename, string destinationFilename, string password, byte[] salt, int iterations)
    {
        AesManaged aes = new AesManaged();
        aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
        aes.KeySize = aes.LegalKeySizes[0].MaxSize;
        // NB: Rfc2898DeriveBytes initialization and subsequent calls to   GetBytes   must be eactly the same, including order, on both the encryption and decryption sides.
        Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);
        aes.Key = key.GetBytes(aes.KeySize / 8);
        aes.IV = key.GetBytes(aes.BlockSize / 8);
        aes.Mode = CipherMode.CBC;
        ICryptoTransform transform = aes.CreateEncryptor(aes.Key, aes.IV);

        using (FileStream destination = new FileStream(destinationFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None))
        {
            using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
            {
                using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    source.CopyTo(cryptoStream);
                }
            }
        }
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

加密/解密大文件 (.NET) 的相关文章

随机推荐

  • 将opencv图像格式转换为PIL图像格式?

    我想转换加载的图像 TestPicture cv2 imread flowers jpg 我想运行一个PIL过滤器 http pillow readthedocs io en 4 0 x reference ImageFilter html
  • 我在构建 Android AOSP 时不小心卸载了 jack 服务器

    我正在我的 ubuntu 14 04 机器上构建 Android Go 的 Android 代码 在构建过程中 我遇到了 jack 服务器的一些问题 最终我卸载了 jack 服务器 意外地 如何再次安装 Jack 服务器 我尝试使用以下命令
  • SQL 是一种什么样的语言?

    SQL 是上下文无关语言还是其他类型的语言 根据https stackoverflow com a 31265136 https stackoverflow com a 31265136SQL 不是常规语言 简短的解释是每个选择查询看起来像
  • 更改自动完成选择的热键

    在 Eclipse 中 我发现 Enter 是从内容辅助 自动完成列表中选择项目的热键非常烦人 特别是在没有行尾分号的 PyDev 中 按 Enter 键换行将给我在自动完成列表中选择的任何内容 Tab 是一个更好的选择热键 因为我不太可能
  • 如何从代码后面打开日期选择器的日历?

    我正在使用 WPF 和 C 来开发我的应用程序 在我的应用程序中 我有两个日期选择器 第一个日期选择器要求用户选择出发日期 第二个日历要求用户选择返回日期 所以我想做的是 在用户选择出发日期后 第二个日期选择器中的日历将打开 我可以知道打开
  • 将多个 QStyledItemDelegate 与样式表一起使用

    我正在使用双调度创建一个样式化的 QTreeView 来解析数据项的特定委托 这非常有效 我对 QStyledItemDelegate 的委托进行了子类化 以利用样式表 使设计人员能够在代码之外设置 UI 样式 不幸的是 我无法解决 CSS
  • 成功提交表单后更新状态后如何滚动到 AMP 顶部?

    我在 AMP 页面中创建了排序功能 现在当我请求对结果进行排序时 以及当我在成功提交表单后更新状态时 页面滚动位置保持不变 我希望每当排序完成后更新状态时页面都会滚动到顶部 这是我的代码
  • 带有遮罩层的 UIVisualEffectView

    我试图模糊 MKMapView 同时在其上方显示圆形蒙版 为了更好地形象化我的意思 你可以找到我当前状态的图片 这几乎显示了我想要的内容 但背景 地图 应该是模糊的 而这张图片中的情况并非如此 我尝试使用 UIVisualEffectVie
  • 为什么Subject.Dispose不处理当前订阅?

    嗨 我已经想了一段时间了Subject
  • 统计图像数量并比较相似度

    我正在编写一个名为 Memory 的游戏 其中包含随机顺序的 8 对图像 16 个图像 游戏开始时 16个必须显示相同的背景图像 玩家单击任何图块后 图块会从背景图像翻转为前景图像 如果两个前景图像相同 它们就会保留 如果两个前景图像不同
  • java中的try-catch-finally块

    根据我的理解 我想遵循最后释放资源的最佳实践 以防止任何连接泄漏 这是我在 HelperClass 中的代码 public static DynamoDB getDynamoDBConnection try dynamoDB new Dyn
  • Java:递归打印钻石

    如何使用 Java 在给定尺寸的情况下递归打印钻石 大小为 5 会产生 到目前为止我拥有的代码 public static void dia int statSize int size int count int statSizeLarge
  • x86 程序集:弹出一个值而不存储它

    在x86汇编中 是否可以从堆栈中删除一个值而不存储它 类似的东西pop word null 我显然可以使用add esp 4 但也许我缺少一个漂亮干净的 cisc 助记符 add esp 4 add rsp 8 is正常 惯用 干净的方式
  • Compact Framework 的 Zip 库选项?

    我的要求 支持 NET Compact Framework 2 0 和Windows Mobile 6 0 设备 只需将内容解压到存储卡上的目录即可 不需要创建 zip 文件 必须能够在企业 商业软件中使用 可以开源 但没有 GPL 或其他
  • 动态删除一系列 Excel 单元格中的空白

    我有一个命名的数据范围 称为 数据 我试图找到一个公式或数组公式 它将返回新的单元格范围中的数据 但会丢失所有空白行 i e data is row x y 1 A 77 2 3 B 23 4 A 100 5 我的新范围是 row x y
  • Android 中没有提示的蓝牙发现

    我可以使用以下代码在没有任何提示的情况下打开 关闭蓝牙 这个需要BLUETOOTH and BLUETOOTH ADMIN权限 boolean isEnabled bluetoothAdapter isEnabled if enable i
  • 即使我安装了它,也没有名为“Kivy”的模块

    据我所知 我已经安装了 Kivy 和所有需要的文件 但我仍然收到此错误消息 我不知道为什么 from kivy app import App from kivy uix gridlayout import GridLayout class
  • 四色定理美国地​​图的Java实现

    我试图为每个状态分配一种颜色 以便没有两个相邻的状态共享相同的颜色 http en wikipedia org wiki Four color theorem http en wikipedia org wiki Four color th
  • 如何将 ICC 添加到现有 PDF 文档

    我有一个使用 CMYK 颜色的现有 PDF 文档 它是使用我获得的特定 ICC 配置文件创建的 如果我在配置文件处于活动状态时打开文档 则颜色明显不同 据我使用各种工具所知 文档中没有嵌入 ICC 配置文件 我想做的是将 ICC 配置文件嵌
  • 加密/解密大文件 (.NET)

    我必须加密 存储然后解密大文件 最好的方法是什么 我听说 RSA 加密很昂贵 建议使用 RSA 加密 AES 密钥 然后使用 AES 密钥加密大文件 任何带有示例的建议都会很棒 一种有机体很大 另一种有机体很小 尽管我们看到它时都知道它很昂