通过C#解密AES时要解密的数据长度无效消息

时间:2019-10-19 21:27:15

标签: c# aes

我有两个使用AES算法的按钮,一个用于加密,另一个用于解密。当我进行加密时很好,但是当我进行解密时,我会遇到此消息错误。

我正在使用Convert.FromBase64String(s),但仍然无法正常工作。

  private void Encryption_Click(object sender, EventArgs e)
        {SaveFileDialog save = new SaveFileDialog();
            save.FileName = "DefaultOutputName.txt"
            save.Filter = "Text File | *.txt";

            if (save.ShowDialog() == DialogResult.OK)

            {

                StreamWriter writer = new StreamWriter(save.OpenFile());

                cipherdata = textBox2.Text;

                plainbytes = Encoding.ASCII.GetBytes(cipherdata);
                plainkey= Encoding.ASCII.GetBytes("0123456789abcdef");
                desobj.Key = plainkey;
                desobj.Mode = CipherMode.CBC;
                desobj.Padding = PaddingMode.PKCS7;
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                CryptoStream cs = new CryptoStream(ms, desobj.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(plainbytes, 0, plainbytes.Length);
                cs.Close();
                cipherbytes = ms.ToArray();
                Convert.ToBase64String(cipherbytes);
                MessageBox.Show(cipherbytes.Length.ToString());
                ms.Close();
                writer.WriteLine(Encoding.ASCII.GetString(cipherbytes));

                writer.Dispose();

                writer.Close();

            }
        }

        private void decryption_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                string s = File.ReadAllText(ofd.FileName);

                cipherbytes = Encoding.ASCII.GetBytes(s); 
                System.IO.MemoryStream ms1 = new System.IO.MemoryStream(cipherbytes);
                CryptoStream cs1 = new CryptoStream(ms1, desobj.CreateDecryptor(), CryptoStreamMode.Read);
                cs1.Read(cipherbytes, 0, cipherbytes.Length);
                plainbytes2 = ms1.ToArray();

                cs1.Close();
                ms1.Close();
                textBox2.Text = Encoding.ASCII.GetString(plainbytes2);
            }
        }

0 个答案:

没有答案