如何使用C#加密/解密.xlsx/.doc文件
本文关键字:xlsx doc 文件 解密 加密 何使用 | 更新日期: 2023-09-27 17:59:48
我正在为Encrtpt/Decrypt文件编写一个应用程序,并为此使用DESCryptoServiceProvider。这似乎适用于文本文件,但当我对.xlsx文件使用相同的应用程序时,生成的加密文件和解密文件会损坏,我无法再打开它。有什么方法可以加密/解密不同类型的文件,如.doc.xls等吗
更新:添加了加密/解密的代码
public static void EncryptFile(string filepath,string fileOutput, string key)
{
FileStream fsInput = new FileStream(filepath, FileMode.Open, FileAccess.Read);
FileStream fsEncrypted = new FileStream(fileOutput, FileMode.Create, FileAccess.Write);
DESCryptoServiceProvider DESc = new DESCryptoServiceProvider();
DESc.Key = ASCIIEncoding.ASCII.GetBytes(key);
DESc.IV = ASCIIEncoding.ASCII.GetBytes(key);
ICryptoTransform desEncrypt = DESc.CreateEncryptor();
CryptoStream cryptoStream = new CryptoStream(fsEncrypted, desEncrypt, CryptoStreamMode.Write);
byte[] byteArrayInput = new byte[fsInput.Length - 1];
fsInput.Read(byteArrayInput, 0, byteArrayInput.Length);
cryptoStream.Write(byteArrayInput, 0, byteArrayInput.Length);
cryptoStream.Close();
fsInput.Close();
fsEncrypted.Close();
}
public static void DecryptFile(string filepath, string fileOutput, string key)
{
DESCryptoServiceProvider DESc = new DESCryptoServiceProvider();
DESc.Key = ASCIIEncoding.ASCII.GetBytes(key);
DESc.IV = ASCIIEncoding.ASCII.GetBytes(key);
FileStream fsread = new FileStream(filepath, FileMode.Open, FileAccess.Read);
ICryptoTransform desDecrypt = DESc.CreateDecryptor();
CryptoStream cryptoStreamDcr = new CryptoStream(fsread, desDecrypt, CryptoStreamMode.Read);
StreamWriter fsDecrypted = new StreamWriter(fileOutput);
fsDecrypted.Write(new StreamReader(cryptoStreamDcr).ReadToEnd());
fsDecrypted.Flush();
fsDecrypted.Close();
}
static void Main(string[] args)
{
EncryptFile(@"C:'test1.xlsx", @"c:'test2.xlsx", "ABCDEFGH");
DecryptFile(@"C:'test2.xlsx", @"c:'test3.xlsx", "ABCDEFGH");
}
您没有正确加密或解密。Encrypt->Decrypt将始终提供与输入相同的文件。如果你发布你的代码,我们可能会帮助你找到其中的错误。
您应该按照Kieren Johnstone的一条评论中的建议使用FileStream
a。此外,加密时不会刷新流——这可能不会自动完成,所以你也应该尝试刷新流。