文件无法正确解密

时间:2010-07-11 18:11:24

标签: c# .net encryption file-io

好的,在这一点上,我已经找到了许多其他问题。现在尝试解密文件时,我没有收到任何异常,但是数据没有正确解密....它会在不抛出异常的情况下完成整个操作,直到我在解密后再次尝试通过组合框访问XML文档。此时会抛出此错误:

发生了意外的文件结束。以下元素未关闭:帐户。第12行,第10位。 当我在Web浏览器中打开文件时,它只有一半的XML节点。发生了什么事?

public partial class Form1 : Form
{
    public string fileName = "passfile.xml";
    public DataSet ds = new DataSet("Account List");
    public DataTable accounts = new DataTable("Accounts");
    public Form1()
    {
        InitializeComponent();
        accountGroupsBox.Enabled = false;
        menuStrip1.Enabled = false;
        button2.Enabled = false;
        Types type = new Types();
        this.accountGroupsBox.Items.AddRange(type.accountTypes);
        accounts.Columns.AddRange(new DataColumn[] {
            new DataColumn("Username"),
            new DataColumn("Password"),
            new DataColumn("Description")});

        dataGridView1.DataSource = accounts;


    }

    private void addNewPasswordToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Form2 addAccount = new Form2(this);
        addAccount.Show();
    }

    private void S_Click(object sender, EventArgs e)
    { //Need to add some code to check for password correctness, for now just unlock the interface
        accountGroupsBox.Enabled = true;
        menuStrip1.Enabled = true;
        button2.Enabled = true;
        label2.Text = "Interface Unlocked";
    }

    private void accountGroupsBox_SelectedIndexChanged(object sender, EventArgs e)
    { //Display the accounts on the datagrid
        accounts.Clear();
        XmlDocument doc = new XmlDocument();
        doc.Load(fileName);
        foreach (XmlNode node in doc.GetElementsByTagName("Account"))
        {
            if (node["AccountType"].InnerText == accountGroupsBox.SelectedItem.ToString())
            {
                DataRow row = accounts.Rows.Add(
                node["Username"].InnerText,
                node["Password"].InnerText,
                node["Description"].InnerText);
            }
        }


    }
    public void Encrypt()
    {   
        string temp = Path.GetTempFileName();
        string path = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
        byte[] pword = Encoding.UTF8.GetBytes(textBox1.Text);
        byte[] hash = SHA256.Create().ComputeHash(pword);
        byte[] iv = MD5.Create().ComputeHash(pword);
        byte[] key = hash;

        using(FileStream fsInput = new FileStream(fileName, FileMode.Open, FileAccess.Read))
        using(SymmetricAlgorithm alg = Aes.Create())
        using(ICryptoTransform enc = alg.CreateEncryptor(key, iv))
        using (FileStream fsOutput = new FileStream(temp, FileMode.Create, FileAccess.Write))
        using (CryptoStream cs = new CryptoStream(fsOutput, enc, CryptoStreamMode.Write))
        {
            try
            {
                byte[] byteInput = new byte[fsInput.Length - 1];
                fsInput.Read(byteInput, 0, byteInput.Length);
                cs.Write(byteInput, 0, byteInput.Length);

                FileInfo old = new FileInfo(fileName);
                FileInfo newer = new FileInfo(temp);
                old.Delete();
                newer.MoveTo(Path.Combine(path, fileName));


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Encryption Error", MessageBoxButtons.OK);

            }
        }


    }
    public void Decrypt()
    {

        byte[] pword = Encoding.UTF8.GetBytes(textBox1.Text);
        byte[] hash = SHA256.Create().ComputeHash(pword);
        byte[] iv = MD5.Create().ComputeHash(pword);
        byte[] key = hash;

        using(FileStream fsInput = new FileStream(fileName, FileMode.Open, FileAccess.Read))
        using(SymmetricAlgorithm alg = Aes.Create())
        using(ICryptoTransform enc = alg.CreateDecryptor(key, iv))
        using (CryptoStream cs = new CryptoStream(fsInput, enc, CryptoStreamMode.Read))
        {
            StreamWriter sw = new StreamWriter(temp);
            sw.Write(new StreamReader(cs).ReadToEnd());
            sw.Flush();
            sw.Close();
        }
        FileInfo encrypted = new FileInfo(fileName);
        FileInfo decrypted = new FileInfo(temp);
        encrypted.Delete();
        decrypted.MoveTo(Path.Combine(path, fileName);

2 个答案:

答案 0 :(得分:2)

当您致电fileName时,旧文件old.Delete();仍处于打开状态。当使用{}块结束时,它将关闭。移动文件删除并重命名为加密方法的末尾。

答案 1 :(得分:0)

正在对打开的文件执行Delete和MoveTo操作。另外,decrypt方法打开“filename”文件两次。你在哪一行抛出异常?