当我解密文本文件时,文本文件变空

时间:2016-11-21 19:52:14

标签: c# windows encryption

伙计们,我是这个网站的新手,我是一个非常新的编程任何帮助都会很棒!谢谢以下是我的加密和解密代码。图像和PDF文件加密和解密没有问题,但文本文件我不知道它在解密后没有在文件中显示任何内容。

   private void encrypt (string input, string output, string strHash )

{
    FileStream inStream, outStream;
    CryptoStream CryStream;

    TripleDESCryptoServiceProvider TDC = new TripleDESCryptoServiceProvider();
    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

    byte[] byteHash, byteTexto;

    inStream = new FileStream(input, FileMode.Open, FileAccess.Read);
    outStream = new FileStream(output, FileMode.OpenOrCreate, FileAccess.Write);

    byteHash = md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strHash));
    byteTexto = File.ReadAllBytes(input);

    md5.Clear();enter code here

    TDC.Key = byteHash;
    TDC.Mode = CipherMode.ECB;

    CryStream = new CryptoStream(outStream, TDC.CreateEncryptor(), CryptoStreamMode.Write);

    int bytesRead;
    long length, position = 0;
    length = inStream.Length;

    while(position < length)
    {
        bytesRead = inStream.Read(byteTexto, 0, byteTexto.Length);
        position += bytesRead;

        CryStream.Write(byteTexto, 0, bytesRead);

    }

    inStream.Close();
    outStream.Close();
}

private void Form1_Load(object sender, EventArgs e)
{

}

private void btnDecrypt_Click(object sender, EventArgs e)
{
    OpenFileDialog open = new OpenFileDialog();
    open.ShowDialog();

    txtLocalDecFile.Text = open.FileName;

    SaveFileDialog save = new SaveFileDialog();
    save.ShowDialog();

    txtNewDecFile.Text = save.FileName;

    decrypt(txtLocalDecFile.Text, txtNewDecFile.Text, key);

}

private void decrypt(string input, string output, string strHash)
{
    FileStream inStream, outStream;
    CryptoStream CryStream;
    TripleDESCryptoServiceProvider TDC = new TripleDESCryptoServiceProvider();
    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

    byte[] byteHash, byteTexto;

    inStream = new FileStream(input, FileMode.Open, FileAccess.Read);
    outStream = new FileStream(output, FileMode.OpenOrCreate, FileAccess.Write);

    byteHash = md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strHash));
    byteTexto = File.ReadAllBytes(input);

    md5.Clear();

    TDC.Key = byteHash;
    TDC.Mode = CipherMode.ECB;

    CryStream = new CryptoStream(outStream, TDC.CreateDecryptor(), CryptoStreamMode.Write);

    int bytesRead;
    long length, position = 0;
    length = inStream.Length;

    while (position < length)
    {
        bytesRead = inStream.Read(byteTexto, 0, byteTexto.Length);
        position += bytesRead;

        CryStream.Write(byteTexto, 0, bytesRead);

    }

    inStream.Close();
    outStream.Close();
}

2 个答案:

答案 0 :(得分:2)

您忘记关闭CryptoStream,这意味着它无法将所有数据刷新到文件中。

关闭流,就像使用inStream和outStream一样关闭流,或者在CryStream上调用FlushFinalBlock()。

文档中有example

答案 1 :(得分:0)

尝试使用AES加密:

http://www.codeproject.com/Articles/769741/Csharp-AES-bits-Encryption-Library-with-Salt

有一个如何加密和解密的例子