C#实现简单的文件加密与解密方式

C#实现简单的文件加密与解密方式攻略

介绍

本文详细讲解如何使用C#语言实现简单的文件加密与解密方式。文件加密是数据保护的一种方法,通过对敏感文件进行加密,确保在未授权的情况下无法访问和解读文件内容。本文讲解将使用对称加密算法 AES 实现文件加密与解密。

实现过程

  1. 导入 System.Security.Cryptography 命名空间。该命名空间提供了对称加密算法的支持。
using System.Security.Cryptography;
  1. 创建一个加解密类。
public class AesEncryption
{
    // 加密密钥
    private static readonly byte[] key = Encoding.UTF8.GetBytes("0123456789abcdefghijklmnopqrstuvwxyz");

    // 初始化向量
    private static readonly byte[] iv = Encoding.UTF8.GetBytes("9876543210zyxwvutsrqponmlkjihgfedcba");

    // 加密方法
    public static void EncryptFile(string inputFile, string outputFile)
    {
        using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
        {
            aes.Key = key;
            aes.IV = iv;

            using (FileStream fsInput = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
            {
                using (FileStream fsOutput = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(fsOutput, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        byte[] buffer = new byte[4096];
                        int read = 0;

                        while ((read = fsInput.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            cryptoStream.Write(buffer, 0, read);
                        }

                        cryptoStream.FlushFinalBlock();
                    }
                }
            }
        }
    }

    // 解密方法
    public static void DecryptFile(string inputFile, string outputFile)
    {
        using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
        {
            aes.Key = key;
            aes.IV = iv;

            using (FileStream fsInput = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
            {
                using (FileStream fsOutput = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(fsOutput, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        byte[] buffer = new byte[4096];
                        int read = 0;

                        while ((read = fsInput.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            cryptoStream.Write(buffer, 0, read);
                        }

                        cryptoStream.FlushFinalBlock();
                    }
                }
            }
        }
    }
}
  1. 调用加密与解密方法。
string inputFile = "path\\to\\input\\file.txt";
string encryptedFile = "path\\to\\encrypted\\file.enc";
string decryptedFile = "path\\to\\decrypted\\file.txt";

// 文件加密
AesEncryption.EncryptFile(inputFile, encryptedFile);

// 文件解密
AesEncryption.DecryptFile(encryptedFile, decryptedFile);

示例

示例1

以下示例将读取 inputfile.txt 中的文本内容,使用 AES 对称加密算法对文本内容进行加密,将加密结果输出到 encryptedfile.txt 中,然后再将 encryptedfile.txt 文件进行解密,并输出到 decryptedfile.txt 中。

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

public class AesEncryption
{
    // 加密密钥
    private static readonly byte[] key = Encoding.UTF8.GetBytes("0123456789abcdefghijklmnopqrstuvwxyz");

    // 初始化向量
    private static readonly byte[] iv = Encoding.UTF8.GetBytes("9876543210zyxwvutsrqponmlkjihgfedcba");

    // 加密方法
    public static void EncryptFile(string inputFile, string outputFile)
    {
        using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
        {
            aes.Key = key;
            aes.IV = iv;

            using (FileStream fsInput = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
            {
                using (FileStream fsOutput = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(fsOutput, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        byte[] buffer = new byte[4096];
                        int read = 0;

                        while ((read = fsInput.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            cryptoStream.Write(buffer, 0, read);
                        }

                        cryptoStream.FlushFinalBlock();
                    }
                }
            }
        }
    }

    // 解密方法
    public static void DecryptFile(string inputFile, string outputFile)
    {
        using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
        {
            aes.Key = key;
            aes.IV = iv;

            using (FileStream fsInput = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
            {
                using (FileStream fsOutput = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(fsOutput, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        byte[] buffer = new byte[4096];
                        int read = 0;

                        while ((read = fsInput.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            cryptoStream.Write(buffer, 0, read);
                        }

                        cryptoStream.FlushFinalBlock();
                    }
                }
            }
        }
    }
}

public class Program
{
    static void Main(string[] args)
    {
        string inputFile = @"C:\data\inputfile.txt";
        string encryptedFile = @"C:\data\encryptedfile.enc";
        string decryptedFile = @"C:\data\decryptedfile.txt";

        // 文件加密
        AesEncryption.EncryptFile(inputFile, encryptedFile);

        // 文件解密
        AesEncryption.DecryptFile(encryptedFile, decryptedFile);

        Console.WriteLine("File encryption and decryption has been completed.");
    }
}

示例2

以下示例将读取指定路径下的 inputfile.jpg图片,使用 AES 对称加密算法对图片进行加密,并将其输出到 encryptedfile.jpg 中,再将 encryptedfile.jpg 文件进行解密,并输出到 decryptedfile.jpg 中。

public class AesEncryption
{
    // 加密密钥
    private static readonly byte[] key = Encoding.UTF8.GetBytes("0123456789abcdefghijklmnopqrstuvwxyz");

    // 初始化向量
    private static readonly byte[] iv = Encoding.UTF8.GetBytes("9876543210zyxwvutsrqponmlkjihgfedcba");

    // 加密方法
    public static void EncryptFile(string inputFile, string outputFile)
    {
        using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
        {
            aes.Key = key;
            aes.IV = iv;

            using (FileStream fsInput = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
            {
                using (FileStream fsOutput = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(fsOutput, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        byte[] buffer = new byte[4096];
                        int read = 0;

                        while ((read = fsInput.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            cryptoStream.Write(buffer, 0, read);
                        }

                        cryptoStream.FlushFinalBlock();
                    }
                }
            }
        }
    }

    // 解密方法
    public static void DecryptFile(string inputFile, string outputFile)
    {
        using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
        {
            aes.Key = key;
            aes.IV = iv;

            using (FileStream fsInput = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
            {
                using (FileStream fsOutput = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(fsOutput, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        byte[] buffer = new byte[4096];
                        int read = 0;

                        while ((read = fsInput.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            cryptoStream.Write(buffer, 0, read);
                        }

                        cryptoStream.FlushFinalBlock();
                    }
                }
            }
        }
    }
}

public class Program
{
    static void Main(string[] args)
    {
        string inputFile = @"C:\data\inputfile.jpg";
        string encryptedFile = @"C:\data\encryptedfile.jpg";
        string decryptedFile = @"C:\data\decryptedfile.jpg";

        // 文件加密
        AesEncryption.EncryptFile(inputFile, encryptedFile);

        // 文件解密
        AesEncryption.DecryptFile(encryptedFile, decryptedFile);

        Console.WriteLine("File encryption and decryption has been completed.");
    }
}

结论

本文以 AES 对称加密算法为例,讲解了 C# 实现简单的文件加密与解密方式攻略。读者可以在实际应用中根据需要,选择不同的加密算法实现更加安全的文件加密功能。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C#实现简单的文件加密与解密方式 - Python技术站

(0)
上一篇 2023年5月15日
下一篇 2023年5月15日

相关文章

  • 将PHP程序中返回的JSON格式数据用gzip压缩输出的方法

    将PHP程序中返回的JSON格式数据用gzip压缩输出的方法是一种优化Web应用性能的方式。下面是详细的攻略步骤: 1. 启用gzip压缩 在PHP应用中启用gzip压缩,需要开启PHP的zlib扩展。可以在php.ini文件中搜索zlib来查看是否已开启。如果没开启,可以手动修改php.ini文件,将以下两行去掉注释: extension=php_zlib…

    C# 2023年6月1日
    00
  • JavaScript学习笔记记录我的旅程

    JavaScript学习笔记记录我的旅程 攻略 1. 学习基础 作为初学者,首先要掌握一些基本的概念和语法,比如: 变量(variable)和数据类型(data type) 运算符(operator) 控制流(if-else、for、while) 函数(function) 这些内容可以通过阅读官方教程或者相关书籍来学习。推荐的书籍有《JavaScript高级…

    C# 2023年6月7日
    00
  • C# Directory.GetDirectories(string path):获取指定目录下的所有子目录路径

    Directory.GetDirectories(string path)方法是C#中用于获取指定路径下所有子目录的静态方法。 具体使用方法如下: 1.导入命名空间 在使用该方法之前,需要先导入System.IO命名空间,以便使用其中提供的Directory类。 using System.IO; 2.方法原型 public static string[] G…

    C# 2023年4月19日
    00
  • C#中利用LINQ to XML与反射把任意类型的泛型集合转换成XML格式字符串的方法

    要利用LINQ to XML与反射将任意类型的泛型集合转换成XML格式字符串,需要按照以下步骤实现: 第一步:创建XML文档对象 首先,我们需要创建一个XDocument对象,这个对象将表示我们要转换的XML文档,然后通过它来操作整个XML文档实现转换。 XDocument doc = new XDocument(new XElement("Roo…

    C# 2023年6月1日
    00
  • 详解WPF如何使用必应地图控件

    详解WPF如何使用必应地图控件 Bing Maps是由微软公司开发的一款Web地图服务,拥有强大的地图绘制和查询功能。它提供了丰富的API和插件,以便为开发者提供全球范围内的地图数据和地图功能。 在WPF项目中,可以使用必应地图控件来在应用程序中嵌入Bing Maps地图。该控件允许您将地图视图嵌入到WPF应用程序中,并提供交互性和属性设置选项。 步骤一:安…

    C# 2023年6月6日
    00
  • .NET 纯分页代码实例

    下面是对“.NET 纯分页代码实例”的完整攻略。 理解分页 在了解分页代码实例之前,首先要理解分页是什么。在网站或者应用中,当数据量太大时,我们需要对其进行分页展示,将数据按照页码分组,方便查看和管理。分页展示涉及到页面布局、URL 地址、数据读取等多种技术,需要综合使用。 实现分页代码 使用PagedList.Mvc插件实现分页 PagedList.Mvc…

    C# 2023年5月31日
    00
  • C#使用游标实现补间函数

    C#使用游标实现补间函数 什么是补间函数 补间函数是一种基于起始点和结束点之间的值之间进行插值的算法,可以让对象在动画过程中平滑移动,使得过渡效果更加自然。补间函数也被称为“插值函数”,是游戏开发、UI设计和动画制作中常见的一种技术。 如何使用游标实现补间函数 在C#中,我们可以通过使用游标来实现补间函数。相对于Unity中提供的插值函数,基于游标的实现更具…

    C# 2023年5月31日
    00
  • 理解ASP.NET Core 中间件(Middleware)

    理解ASP.NET Core 中间件(Middleware) ASP.NET Core中间件是一个处理HTTP请求和响应的组件。中间件可以在请求到达控制器之前或响应返回客户端之前执行一些操作。在本文中,我们将介绍ASP.NET Core中间件的概念、使用方法和示例。 中间件的概念 中间件是一个处理HTTP请求和响应的组件。中间件可以在请求到达控制器之前或响应…

    C# 2023年5月16日
    00
合作推广
合作推广
分享本页
返回顶部