如何正确使用memorystream,cryptostream和utf8编码对数据进行加密和解密?

时间:2018-07-09 10:29:33

标签: c# encryption

实际上,我已经用c#编写了该程序的编码,但是当加密部分为空时,我不能孤独地解密我的加密数据。这是因为我的byte []密码数据在较早的部分为空。如何纠正我的编码? 我将此程序用于更大的文件。需要它更快,更精确。

    private void buttonEncrypt_Click(object sender, EventArgs e)
    {
        AesCryptoServiceProvider triple = new AesCryptoServiceProvider();
        UTF8Encoding u = new UTF8Encoding();            

        triple.Key = Encoding.ASCII.GetBytes("1234567890123456");  
        triple.Mode = CipherMode.ECB;
        triple.Padding = PaddingMode.Zeros;

        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, triple.CreateEncryptor(), CryptoStreamMode.Write);            

        encrypted = Encoding.UTF8.GetBytes(textBoxOpen1.Text);
        cs.Write(encrypted, 0, encrypted.Length);
        cs.Close();

        cipherdata = ms.ToArray();
        ms.Close();

        textBoxEncrypt.Text = Encoding.UTF8.GetString(cipherdata); 
        MessageBox.Show(" Done encrypting ");
    }

    private void buttonDecrypt_Click(object sender, EventArgs e)
    {
        MemoryStream ms = new MemoryStream();

        AesCryptoServiceProvider triple = new AesCryptoServiceProvider();
        UTF8Encoding u = new UTF8Encoding();
        //MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
        //chipherdata = textBox1.Text;

        triple.Key = Encoding.ASCII.GetBytes("1234567890123456");          //md5.ComputeHash(u.GetBytes(textBox3.Text));
        triple.Mode = CipherMode.ECB;
        triple.Padding = PaddingMode.Zeros;

        MemoryStream ms1 = new MemoryStream(cipherdata);
        CryptoStream cs1 = new CryptoStream(ms1, triple.CreateDecryptor(), CryptoStreamMode.Read);

        //decrypted = Encoding.UTF8.GetBytes(textBoxOpen2.Text);

        cs1.Read(cipherdata, 0, cipherdata.Length);
        recipherdata = ms1.ToArray();
        cs1.Close();

        ms1.Close();

        textBoxDecrypt.Text = Encoding.UTF8.GetString(recipherdata);
        MessageBox.Show(" Done decrypting ");
    }

0 个答案:

没有答案