Нужен простой алгоритм шифрования - C#

Узнай цену своей работы

Формулировка задачи:

Привет всем . Помогите сделать любое не сложное а скорей даже простое (что обычные юзеры нечего не поняли) шифрование текста . А именно у меня есть код который вводимый юзером текст сохраняет в файле . как мне сделать чтоб сохранял он его в шифрованном виде ?
Листинг программы
  1. File.AppendAllText("C:\\Test\\List.ini", txtTest.Text + "\r\n");
И есть код который текст из этого файла помещает в текст бокс . И как сделать чтоб помещало в текст бокс уже расшифрованный текст ?
Листинг программы
  1. txtLog.Text = System.IO.File.ReadAllText("C:\\Test\\List.ini");
Надеюсь у меня правильно получилось всё это расписать . Всем спасибо за помощь .

Решение задачи: «Нужен простой алгоритм шифрования»

textual
Листинг программы
  1. using System;
  2. using System.IO;
  3. using System.Security.Cryptography;
  4. using System.Text;
  5.  
  6. namespace MyPasswordManager
  7. {
  8.     public class Crypto
  9.     {
  10.         private static readonly byte[] Salt = Encoding.ASCII.GetBytes("o6806642kbM7c5");
  11.  
  12.         /// <summary>
  13.         /// Encrypt the given string using AES.  The string can be decrypted using
  14.         /// DecryptStringAES().  The sharedSecret parameters must match.
  15.         /// </summary>
  16.         /// <param name="plainText">The text to encrypt.</param>
  17.         /// <param name="sharedSecret">A password used to generate a key for encryption.</param>
  18.         public static string EncryptStringAES(string plainText, string sharedSecret)
  19.         {
  20.             if (string.IsNullOrEmpty(plainText))
  21.                 throw new ArgumentNullException("plainText");
  22.             if (string.IsNullOrEmpty(sharedSecret))
  23.                 throw new ArgumentNullException("sharedSecret");
  24.  
  25.             string outStr;                       // Encrypted string to return
  26.             RijndaelManaged aesAlg = null;              // RijndaelManaged object used to encrypt the data.
  27.  
  28.             try
  29.             {
  30.                 // generate the key from the shared secret and the salt
  31.                 var key = new Rfc2898DeriveBytes(sharedSecret, Salt);
  32.  
  33.                 // Create a RijndaelManaged object
  34.                 aesAlg = new RijndaelManaged();
  35.                 aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
  36.  
  37.                 // Create a decryptor to perform the stream transform.
  38.                 ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
  39.  
  40.                 // Create the streams used for encryption.
  41.                 using (var msEncrypt = new MemoryStream())
  42.                 {
  43.                     // prepend the IV
  44.                     msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
  45.                     msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
  46.                     using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
  47.                     {
  48.                         using (var swEncrypt = new StreamWriter(csEncrypt))
  49.                         {
  50.                             //Write all data to the stream.
  51.                             swEncrypt.Write(plainText);
  52.                         }
  53.                     }
  54.                     outStr = Convert.ToBase64String(msEncrypt.ToArray());
  55.                 }
  56.             }
  57.             finally
  58.             {
  59.                 // Clear the RijndaelManaged object.
  60.                 if (aesAlg != null)
  61.                     aesAlg.Clear();
  62.             }
  63.  
  64.             // Return the encrypted bytes from the memory stream.
  65.             return outStr;
  66.         }
  67.  
  68.         /// <summary>
  69.         /// Decrypt the given string.  Assumes the string was encrypted using
  70.         /// EncryptStringAES(), using an identical sharedSecret.
  71.         /// </summary>
  72.         /// <param name="cipherText">The text to decrypt.</param>
  73.         /// <param name="sharedSecret">A password used to generate a key for decryption.</param>
  74.         public static string DecryptStringAES(string cipherText, string sharedSecret)
  75.         {
  76.             if (string.IsNullOrEmpty(cipherText))
  77.                 throw new ArgumentNullException("cipherText");
  78.             if (string.IsNullOrEmpty(sharedSecret))
  79.                 throw new ArgumentNullException("sharedSecret");
  80.  
  81.             // Declare the RijndaelManaged object
  82.             // used to decrypt the data.
  83.             RijndaelManaged aesAlg = null;
  84.  
  85.             // Declare the string used to hold
  86.             // the decrypted text.
  87.             string plaintext;
  88.  
  89.             try
  90.             {
  91.                 // generate the key from the shared secret and the salt
  92.                 var key = new Rfc2898DeriveBytes(sharedSecret, Salt);
  93.  
  94.                 // Create the streams used for decryption.                
  95.                 byte[] bytes = Convert.FromBase64String(cipherText);
  96.                 using (var msDecrypt = new MemoryStream(bytes))
  97.                 {
  98.                     // Create a RijndaelManaged object
  99.                     // with the specified key and IV.
  100.                     aesAlg = new RijndaelManaged();
  101.                     aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
  102.                     // Get the initialization vector from the encrypted stream
  103.                     aesAlg.IV = ReadByteArray(msDecrypt);
  104.                     // Create a decrytor to perform the stream transform.
  105.                     ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
  106.                     using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
  107.                     {
  108.                         using (var srDecrypt = new StreamReader(csDecrypt))
  109.  
  110.                             // Read the decrypted bytes from the decrypting stream
  111.                             // and place them in a string.
  112.                             plaintext = srDecrypt.ReadToEnd();
  113.                     }
  114.                 }
  115.             }
  116.             finally
  117.             {
  118.                 // Clear the RijndaelManaged object.
  119.                 if (aesAlg != null)
  120.                     aesAlg.Clear();
  121.             }
  122.  
  123.             return plaintext;
  124.         }
  125.  
  126.         private static byte[] ReadByteArray(Stream s)
  127.         {
  128.             var rawLength = new byte[sizeof(int)];
  129.             if (s.Read(rawLength, 0, rawLength.Length) == rawLength.Length)
  130.             {
  131.                 var buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
  132.                 if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
  133.                 {
  134.                     throw new SystemException("Did not read byte array properly");
  135.                 }
  136.  
  137.                 return buffer;
  138.             }
  139.  
  140.             throw new SystemException("Stream did not contain properly formatted byte array");
  141.         }
  142.     }
  143. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

12   голосов , оценка 4.167 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут