2011-06-22 47 views
0

我正在为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"); 
    } 

回答

0

您没有加密或解密正确。加密 - >解密将始终提供与输入相同的文件。如果您发布代码,我们可能会协助查找其中的错误。

+0

相同的代码适用于.txt文件,但不适用于.xlsx,所以我假设encruption/decryption正确地发生,但是excel需要一些不同的东西。 – Kapil

+0

不错,我很害怕。可能你的代码只能用于某些文本文件,并且“出现”可以正常工作,而不是二进制文件,如果代码只是简单地加密/解密文件,那么这会是一个错误。 –

+1

是的,因为我怀疑:你正在使用'StreamReader'或'StreamWriter'。他们读写文本文件。直接使用'FileStream'对象。编辑:奇怪,你正在做的加密正确,但使用文本模式的解密。解密需要修复:) –

0

您应该使用FileStream a,如Kieren Johnstone的评论中所建议的那样。此外,加密时不会刷新流 - 这可能不会自动完成,因此您应该尝试刷新流。