C# 中的文件加密和解密






4.19/5 (38投票s)
演示如何使用 C# 加密和解密任何文件类型。
引言
本文演示如何使用 C# 加密和解密任何类型的文件。
背景
最近,我需要找到一种简单的方法来加密和解密任何类型(我实际上需要加密图像和文本文件)和任何大小的文件。我在网上找到了数百个示例,其中许多根本无法工作,或者在某些文件类型上抛出错误。
最终,我使用 Rijndael 加密算法编写了以下两个方法。它们只需要你传递原始文件和目标文件的完整路径。它们都需要使用 System.Security
、System.Security.Cryptography
、System.Runtime.InteropServices
和 System.Text.RegularExpressions
命名空间。
不幸的是,由于我查看了网上如此多的示例,而且实际上很久以前就完成了所有这些工作,所以我记不清哪些代码片段最初是由谁编写的。所以,如果你认出了其中的一部分,请留下评论,以便你的工作不会被忽视。
使用代码
有两种方法:encryptFile
和 decryptFile
。它们都需要你传入源文件和目标文件的文件名和路径作为字符串。重要的是,用户必须具有创建加密文件的必要文件权限。
///<summary>
/// Steve Lydford - 12/05/2008.
///
/// Encrypts a file using Rijndael algorithm.
///</summary>
///<param name="inputFile"></param>
///<param name="outputFile"></param>
private void EncryptFile(string inputFile, string outputFile)
{
try
{
string password = @"myKey123"; // Your Key Here
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
string cryptFile = outputFile;
FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateEncryptor(key, key),
CryptoStreamMode.Write);
FileStream fsIn = new FileStream(inputFile, FileMode.Open);
int data;
while ((data = fsIn.ReadByte()) != -1)
cs.WriteByte((byte)data);
fsIn.Close();
cs.Close();
fsCrypt.Close();
}
catch
{
MessageBox.Show("Encryption failed!", "Error");
}
}
///<summary>
/// Steve Lydford - 12/05/2008.
///
/// Decrypts a file using Rijndael algorithm.
///</summary>
///<param name="inputFile"></param>
///<param name="outputFile"></param>
private void DecryptFile(string inputFile, string outputFile)
{
{
string password = @"myKey123"; // Your Key Here
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateDecryptor(key, key),
CryptoStreamMode.Read);
FileStream fsOut = new FileStream(outputFile, FileMode.Create);
int data;
while ((data = cs.ReadByte()) != -1)
fsOut.WriteByte((byte)data);
fsOut.Close();
cs.Close();
fsCrypt.Close();
}
}