用C#解密文本文件

时间:2018-12-20 12:12:28

标签: c# wpf encryption aes

基本上,我正在尝试打开一个以前使用AesManaged加密类加密的文本文件。这是我的代码:

private void DecryptText(object sender, RoutedEventArgs e)
        {

              EnterTextBox.Clear();


                OpenFileDialog ofd = new OpenFileDialog();

                ofd.DefaultExt = ".txt";

                string file = ofd.DefaultExt = ".txt";


                if (ofd.ShowDialog() == true)
                {

                    str = ofd.FileName;

                    EnterTextBox.Text = File.ReadAllText(str);
                }
                string test = ofd.SafeFileName;



                string thump = DecryptTextFromFile(test, key1, iv1);
                MessageBox.Show("Decrypted text: " + thump);
        }

我尝试使用此方法执行此操作:

public static string DecryptTextFromFile(String FileName, byte[] Key, byte[] IV)
        {
            try
            {
                FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate);

                CryptoStream cStream = new CryptoStream(fStream, new AesManaged().CreateDecryptor(Key, IV), CryptoStreamMode.Read);

                StreamReader sReader = new StreamReader(cStream);

                string val = sReader.ReadLine();


                //MessageBox.Show(val);
                sReader.Close();
                cStream.Close();
                fStream.Close();


                return val;

            }

            catch (CryptographicException e)
            {

                Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
                return null;

            }

            catch (UnauthorizedAccessException e)
            {

                Console.WriteLine("A file error occurred: {0}", e.Message);
                return null;

            }

        }

这是我不断遇到的错误,不确定如何解决。

A Cryptographic error occurred: Padding is invalid and cannot be removed.

在此方面的任何帮助将不胜感激,因为我对此并不陌生,也不确定自己在做什么。 谢谢

这就是我加密文本文件的方式...

 try
            {

                FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate);//Create/Open File

                CryptoStream cStream = new CryptoStream(fStream, new AesManaged().CreateEncryptor(Key, IV), CryptoStreamMode.Write);

                StreamWriter sWriter = new StreamWriter(cStream);

                sWriter.WriteLine(Data);

                sWriter.Close();
                cStream.Close();
                fStream.Close();

                string Final = DecryptTextFromFile(FileName, Key, IV);



            }

            catch (CryptographicException e)
            {

                Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);

            }

            catch (UnauthorizedAccessException e)
            {

                Console.WriteLine("A file error occurred: {0}", e.Message);

            }

编辑

0 个答案:

没有答案