如何使用C#加密/解密.xlsx / .doc文件

时间:2011-06-22 08:24:26

标签: c#

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

你应该按照Kieren Johnstone的一条评论中的建议使用FileStream a。此外,您在加密时不会刷新流 - 这可能无法自动完成,因此您也应该尝试刷新流。