1147 字
6 分钟
C#文件加密解密工具类
2025-12-21

完整代码实现#

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace CryptoHelp
{
/// <summary>
/// 异常处理类
/// </summary>
public class CryptoHelpException : ApplicationException
{
public CryptoHelpException(string msg) : base(msg) { }
}
public class CryptoHelp
{
private const ulong FC_TAG = 0xFC010203040506CF;
private const int BUFFER_SIZE = 128 * 1024;
/// <summary>
/// 检验两个Byte数组是否相同
/// </summary>
private static bool CheckByteArrays(byte[] b1, byte[] b2)
{
if (b1.Length == b2.Length)
{
for (int i = 0; i < b1.Length; ++i)
{
if (b1[i] != b2[i])
return false;
}
return true;
}
return false;
}
/// <summary>
/// 创建Rijndael SymmetricAlgorithm
/// </summary>
private static SymmetricAlgorithm CreateRijndael(string password, byte[] salt)
{
PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, salt, "SHA256", 1000);
SymmetricAlgorithm sma = Rijndael.Create();
sma.KeySize = 256;
sma.Key = pdb.GetBytes(32);
sma.Padding = PaddingMode.PKCS7;
return sma;
}
/// <summary>
/// 加密文件随机数生成
/// </summary>
private static RandomNumberGenerator rand = new RNGCryptoServiceProvider();
/// <summary>
/// 生成指定长度的随机Byte数组
/// </summary>
private static byte[] GenerateRandomBytes(int count)
{
byte[] bytes = new byte[count];
rand.GetBytes(bytes);
return bytes;
}
/// <summary>
/// 加密文件
/// </summary>
public static void EncryptFile(string inFile, string outFile, string password)
{
using (FileStream fin = File.OpenRead(inFile),
fout = File.OpenWrite(outFile))
{
long lSize = fin.Length;
byte[] bytes = new byte[BUFFER_SIZE];
int read = -1;
// 获取IV和salt
byte[] IV = GenerateRandomBytes(16);
byte[] salt = GenerateRandomBytes(16);
// 创建加密对象
SymmetricAlgorithm sma = CryptoHelp.CreateRijndael(password, salt);
sma.IV = IV;
// 在输出文件开始部分写入IV和salt
fout.Write(IV, 0, IV.Length);
fout.Write(salt, 0, salt.Length);
// 创建散列加密
HashAlgorithm hasher = SHA256.Create();
using (CryptoStream cout = new CryptoStream(fout, sma.CreateEncryptor(), CryptoStreamMode.Write),
chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))
{
BinaryWriter bw = new BinaryWriter(cout);
bw.Write(lSize);
bw.Write(FC_TAG);
// 读写字节块到加密流缓冲区
while ((read = fin.Read(bytes, 0, bytes.Length)) != 0)
{
cout.Write(bytes, 0, read);
chash.Write(bytes, 0, read);
}
chash.Flush();
chash.Close();
// 读取散列
byte[] hash = hasher.Hash;
cout.Write(hash, 0, hash.Length);
cout.Flush();
cout.Close();
}
}
}
/// <summary>
/// 解密文件
/// </summary>
public static void DecryptFile(string inFile, string outFile, string password)
{
using (FileStream fin = File.OpenRead(inFile),
fout = File.OpenWrite(outFile))
{
byte[] bytes = new byte[BUFFER_SIZE];
int read = -1;
int outValue = 0;
byte[] IV = new byte[16];
fin.Read(IV, 0, 16);
byte[] salt = new byte[16];
fin.Read(salt, 0, 16);
SymmetricAlgorithm sma = CryptoHelp.CreateRijndael(password, salt);
sma.IV = IV;
HashAlgorithm hasher = SHA256.Create();
using (CryptoStream cin = new CryptoStream(fin, sma.CreateDecryptor(), CryptoStreamMode.Read),
chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))
{
BinaryReader br = new BinaryReader(cin);
long lSize = br.ReadInt64();
ulong tag = br.ReadUInt64();
if (FC_TAG != tag)
throw new CryptoHelpException("文件被破坏或者密码不正确");
long numReads = lSize / BUFFER_SIZE;
long slack = (long)lSize % BUFFER_SIZE;
for (int i = 0; i < numReads; ++i)
{
read = cin.Read(bytes, 0, bytes.Length);
fout.Write(bytes, 0, read);
chash.Write(bytes, 0, read);
outValue += read;
}
if (slack > 0)
{
read = cin.Read(bytes, 0, (int)slack);
fout.Write(bytes, 0, read);
chash.Write(bytes, 0, read);
outValue += read;
}
chash.Flush();
chash.Close();
byte[] curHash = hasher.Hash;
byte[] oldHash = new byte[hasher.HashSize / 8];
read = cin.Read(oldHash, 0, oldHash.Length);
if ((oldHash.Length != read) || (!CheckByteArrays(oldHash, curHash)))
throw new CryptoHelpException("文件被破坏");
if (outValue != lSize)
throw new CryptoHelpException("文件大小不匹配");
fout.Flush();
fout.Close();
}
}
}
/// <summary>
/// 解密文件并返回字符串
/// </summary>
public static string DecryptFileToString(string inFile, string outFile, string password)
{
string result = "";
DecryptFile(inFile, outFile, password);
using (StreamReader sr = new StreamReader(outFile))
{
result = sr.ReadToEnd();
}
return result;
}
}
}

核心功能解析#

1. 加密流程#

  1. 初始化阶段

    • 创建文件输入输出流
    • 生成16字节的随机IV和salt
    • 创建Rijndael加密对象
  2. 加密阶段

    • 将IV和salt写入输出文件
    • 创建加密流和哈希流
    • 读取源文件并加密
    • 计算并写入文件哈希值

2. 解密流程#

  1. 初始化阶段

    • 读取IV和salt
    • 创建解密对象
    • 验证文件标记
  2. 解密阶段

    • 解密文件内容
    • 验证文件完整性
    • 写入解密后的内容

使用示例#

try
{
// 加密文件
CryptoHelp.EncryptFile("source.txt", "encrypted.dat", "password123");
// 解密文件
CryptoHelp.DecryptFile("encrypted.dat", "decrypted.txt", "password123");
// 解密并读取为字符串
string content = CryptoHelp.DecryptFileToString("encrypted.dat", "temp.txt", "password123");
}
catch (CryptoHelpException ex)
{
Console.WriteLine($"加密解密错误: {ex.Message}");
}

安全特性#

  1. 加密算法

    • 使用Rijndael(AES)算法
    • 256位密钥长度
    • PKCS7填充模式
  2. 密钥派生

    • 使用PasswordDeriveBytes
    • SHA-256哈希算法
    • 1000次迭代
  3. 完整性验证

    • SHA-256文件哈希
    • 文件标记验证
    • 文件大小校验

性能优化#

  1. 缓冲区处理

    • 128KB缓冲区
    • 流式处理
    • 内存优化
  2. 资源管理

    • using语句
    • 及时释放资源
    • 流的正确关闭

注意事项#

  1. 密码安全

    • 使用强密码
    • 避免硬编码
    • 定期更换
  2. 错误处理

    • 异常捕获
    • 完整性验证
    • 错误日志
  3. 文件操作

    • 权限检查
    • 路径验证
    • 备份重要文件

总结#

这个加密解密工具类提供了完整的文件安全处理方案,具有以下特点:

  1. 安全性高

    • 强加密算法
    • 完整验证机制
    • 随机性保证
  2. 功能完整

    • 文件加密解密
    • 字符串读取
    • 异常处理
  3. 性能优化

    • 缓冲区处理
    • 流式操作
    • 资源管理
  4. 易于使用

    • 简单接口
    • 清晰文档
    • 完整示例

该工具类适合用于需要保护敏感文件的场景,如配置文件加密、数据传输加密等。通过合理使用,可以有效保护文件内容的安全性。

C#文件加密解密工具类
https://non266.top/posts/cryptohelp/
作者
non_no266
发布于
2025-12-21
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

封面
示例歌曲
示例艺术家
封面
示例歌曲
示例艺术家
0:00 / 0:00