我正在爲Encrtpt/Decrypt文件編寫應用程序,並使用DESCryptoServiceProvider來達到此目的。這似乎適用於文本文件,但是當我爲.xlsx文件使用相同的應用程序時,生成的加密文件和解密文件被損壞,我無法再打開它。有沒有什麼辦法可以encryt /解密不同類型的文件像.doc..xls等如何使用C#加密/解密.xlsx/.doc文件
更新:增加了代碼加密/解密
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");
}
相同的代碼適用於.txt文件,但不適用於.xlsx,所以我假設encruption/decryption正確地發生,但是excel需要一些不同的東西。 – Kapil
不錯,我很害怕。可能你的代碼只能用於某些文本文件,並且「出現」可以正常工作,而不是二進制文件,如果代碼只是簡單地加密/解密文件,那麼這會是一個錯誤。 –
是的,因爲我懷疑:你正在使用'StreamReader'或'StreamWriter'。他們讀寫文本文件。直接使用'FileStream'對象。編輯:奇怪,你正在做的加密正確,但使用文本模式的解密。解密需要修復:) –