Спрашивающий
System.Security.Cryptography.CryptographicException: "Плохие данные. "

Вопрос
-
Всем привет, я новичок и ещё не полностью разобрался как всё работает. Есть шифратор и дешифратор. Шифратор зашифровывает текст в файл txt, а дешифратор должен его расшифровать, но постоянно выходит ошибка System.Security.Cryptography.CryptographicException: "Плохие данные.". Также в переменной sa2 разные ключи. Как сделать так, чтобы были одинаковые ключи?
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Security.Cryptography; using System.IO; namespace Encoder { public partial class Form1 : Form { public Form1() { InitializeComponent(); } string str; byte[] key; byte[] te; byte[] cipherbytes; private void button1_Click(object sender, EventArgs e) { SymmetricAlgorithm sa = TripleDES.Create(); sa.GenerateKey(); key = sa.Key; sa.Mode = CipherMode.ECB; sa.Padding = PaddingMode.PKCS7; MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, sa.CreateEncryptor(), CryptoStreamMode.Write); byte[] plainbytes = Encoding.Default.GetBytes(textBox1.Text); cs.Write(plainbytes, 0, plainbytes.Length); cs.Close(); cipherbytes = ms.ToArray(); ms.Close(); str = Encoding.Default.GetString(cipherbytes); textBox1.Text = str; te = new Byte[str.Length]; te = Encoding.Default.GetBytes(str); SymmetricAlgorithm sa2 = TripleDES.Create(); sa2.Key = key; sa2.Mode = CipherMode.ECB; sa2.Padding = PaddingMode.PKCS7; MemoryStream ms2 = new MemoryStream(te); CryptoStream cs2 = new CryptoStream(ms2, sa2.CreateDecryptor(), CryptoStreamMode.Read); StreamWriter file = new StreamWriter("my_file.txt"); file.WriteLine(textBox1.Text); file.Close(); byte[] plainbytes2 = new Byte[te.Length]; cs2.Read(plainbytes2, 0, te.Length); cs2.Close(); ms2.Close(); textBox1.Text = Encoding.Default.GetString(plainbytes2); } } }
Шифратор работает и зашифровывает файлы в txt
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Security.Cryptography; using System.IO; namespace ConsoleApp1 { class Program { static void Main(string[] args) { string str; byte[] key; Byte[] te; byte[] cipherbytes; StreamReader file = new StreamReader("my_file.txt"); // Объявляем переменную A. string A; //В переменную А считываем содержимое файла A = file.ReadToEnd(); SymmetricAlgorithm sa = TripleDES.Create(); sa.GenerateKey(); key = sa.Key; sa.Mode = CipherMode.ECB; sa.Padding = PaddingMode.PKCS7; MemoryStream ms = new MemoryStream(); cipherbytes = ms.ToArray(); str = Encoding.Default.GetString(cipherbytes); te = new Byte[str.Length]; te = Encoding.Default.GetBytes(str); SymmetricAlgorithm sa2 = TripleDES.Create(); sa2.Key = key; sa2.Mode = CipherMode.ECB; sa2.Padding = PaddingMode.PKCS7; MemoryStream ms2 = new MemoryStream(te); CryptoStream cs2 = new CryptoStream(ms2, sa2.CreateDecryptor(), CryptoStreamMode.Read); byte[] plainbytes2 = new Byte[te.Length]; cs2.Read(plainbytes2, 0, te.Length); cs2.Close(); ms2.Close(); //Закрываем поток file.Close(); //Выводим переменную A в окно консольного приложения Console.WriteLine(A); //Осуществим задержку экрана перед закрытием Console.ReadKey(); } } }
Дешифратор постоянно выводить ошибку в строк cs2.Close();
- Изменено Toschyk 22 ноября 2022 г. 2:33
22 ноября 2022 г. 2:32
Все ответы
-
Здравствуйте,
Посмотрите ответ от Iridium'a в этой теме
Если Вам помог чей-либо ответ, пожалуйста, не забывайте жать на кнопку "Предложить как ответ" или "Проголосовать за полезное сообщение" Мнения, высказанные здесь, являются отражение моих личных взглядов, а не позиции корпорации Microsoft. Вся информация предоставляется "как есть" без каких-либо гарантий.
22 ноября 2022 г. 17:17Модератор