我制作了一个控制台应用程序来解密文件。请参阅屏幕截图以获取详细错误消息。
如果您复制粘贴代码在控制台应用程序中。你应该能够调试。
1)需要创建文件夹SourceFolder \ Newfolder \和一个新的txt文件destination.txt
2)需要为C:\ DestinationFolder \ source.txt创建文件夹(加密文件不能在这里附加文件,希望你能做到一个
using System;
using System.IO;
using System.Security.Cryptography;
namespace ConsoleApp5
{
class Program
{
//SALT is a random data that is used as addition to a password to encrypt data
// The primary function is to protect against lists of often used password
private static readonly byte[] SALT = new byte[] {0x26,0xdc,0xff,0x76,0x76,
0xad,0xed,0x7a,0x64,0xc5,0xfe
,0x20,0xaf,0x4d,0x08,0x3c};
static void Main(string[] args)
{
//Need to make a SourceFolder and but the file in there abc.txt
string path = @"C:\SourceFolder\New folder\";
string[] txtFile = Directory.GetFiles(path, "*.txt");
string fileinnn = txtFile[0];
//Get the filepath of the decrypted file. Need to make this folder and add a new file that is what i am donig for now for this cosole app
string filepathDecrypted = @"C:\DestinationFolder\destination.txt"; //this is a new file need to create
//Get the password
string encrytionKey = "password.";
Decrypt(fileinnn, filepathDecrypted, encrytionKey);
}
public static void Decrypt(string fileIn, string fileOut, string Password)
{
//open filestreat for encrypted source file
using (System.IO.FileStream fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read))
{
using (System.IO.FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write))
{
try
{
//Create Key and IV from the password with the SALT
Rfc2898DeriveBytes pdf = new Rfc2898DeriveBytes(Password, SALT);
//Create a symmetric algorithm with Rijndael
Rijndael alg = Rijndael.Create();
alg.Padding = PaddingMode.PKCS7;
//alg.BlockSize = 128;
//SET key and IV
alg.Key = pdf.GetBytes(32);
alg.IV = pdf.GetBytes(16);
//Create a cryptoStream
using (CryptoStream cs = new CryptoStream(fsOut, alg.CreateDecryptor(), CryptoStreamMode.Write))
{
//Intialize the buffer and process the input in chunks
// this is done to avoid reading the whole file which is huge and memory consumption.
int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int bytesRead;
do
{ //read a chunck of data from the input file
bytesRead = fsIn.Read(buffer, 0, bufferLen);
//Decrypt it
cs.Write(buffer, 0, bytesRead);
}
while (bytesRead != 0);
//close everything
cs.Close(); //this is where it throws exception
fsOut.Close();
fsIn.Close();
}
}
catch (Exception ex)
{
var error = ex.Message;
throw;
}
}
}
}
}
}