Text Encrypt and Decrypt With a Specified Key

This software allows you to encrypt and decrypt text with a specified key using C#.

Introduction

This software allows you to encrypt and decrypt text with a specified key, yielding an encoded message, and decode the encrypted messages, recovering the original text.

Background

The basic idea of this project is to save data from hackers. When you send a message using encryption, no one can read the text without having the encrypter software and key that you use. You want to send a mail message that can be read by many people (family, friends, colleagues and so on). When you send a message using an unsecured channel (public mail server, ICQ and so on), you use this software.

Using the Code

Use these namespaces in your code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Drawing;  
  5. using System.Text;  
  6. using System.Windows.Forms;  
  7. using System.IO;  
  8. using System.Security.Cryptography;  
 Use this code for encrypting and decrypting text
  1. namespace Encrypter  
  2. {  
  3.     public partial class Form1 : Form  
  4.     {  
  5.         public Form1()  
  6.         {  
  7.             InitializeComponent();  
  8.         }  
  9.         string key, EnValue;  
  10.   
  11.         private void Form1_Load(object sender, EventArgs e)  
  12.         {  
  13.             txtKey.Text = "o7x8y6";  
  14.         }  
  15.   
  16.         private void btnEncrypt_Click(object sender, EventArgs e)  
  17.          {  
  18.             key = Convert.ToString(txtKey.Text);  
  19.             EnValue = Convert.ToString(txtToEncript.Text);  
  20.   
  21.             if (key != "" && EnValue!="" )  
  22.             {  
  23.                 txtResult.Text=EncryptStringAES(EnValue, key);  
  24.             }  
  25.             else  
  26.             {  
  27.                 lblResult.Text = "Enter text to Encrypt";  
  28.                 return;  
  29.             }  
  30.         }  
  31.   
  32.         private void btnDecript_Click(object sender, EventArgs e)  
  33.         {  
  34.                EnValue = Convert.ToString(txtResult.Text);  
  35.                key = Convert.ToString(txtKey.Text);  
  36.   
  37.             if (key != "" && EnValue != "")  
  38.             {  
  39.                 txtToEncript.Text = DecryptStringAES(EnValue,key);  
  40.             }  
  41.             else  
  42.             {  
  43.                 lblResult.Text = "Enter text to Decrypt";  
  44.                 return;  
  45.             }  
  46.         }  
  47.   
  48.         private void btnExit_Click(object sender, EventArgs e)  
  49.         {  
  50.             Application.Exit();  
  51.         }  
  52.   
  53.         private static byte[] _salt = Encoding.ASCII.GetBytes("o6806642kbM7c5");  
  54.   
  55.         /// <summary>  
  56.         /// Encrypt the given string using AES.  The string can be decrypted using  
  57.         /// DecryptStringAES().  The sharedSecret parameters must match.  
  58.         /// </summary>  
  59.         /// <param name="plainText">The text to encrypt.</param>  
  60.         /// <param name="sharedSecret">A password used to generate a key for encryption.</param>  
  61.         public static string EncryptStringAES(string plainText, string sharedSecret)  
  62.         {  
  63.             if (string.IsNullOrEmpty(plainText))  
  64.                 throw new ArgumentNullException("plainText");  
  65.             if (string.IsNullOrEmpty(sharedSecret))  
  66.                 throw new ArgumentNullException("sharedSecret");  
  67.   
  68.             string outStr = null;                 // Encrypted string to return  
  69.             RijndaelManaged aesAlg = null;        // RijndaelManaged object used to encrypt the data.  
  70.   
  71.             try  
  72.             {  
  73.                 // generate the key from the shared secret and the salt  
  74.                 Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);  
  75.   
  76.                 // Create a RijndaelManaged object  
  77.                 aesAlg = new RijndaelManaged();  
  78.                 aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);  
  79.   
  80.                 // Create a decryptor to perform the stream transform.  
  81.                 ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);  
  82.   
  83.                 // Create the streams used for encryption.  
  84.                 using (MemoryStream msEncrypt = new MemoryStream())  
  85.                 {  
  86.                     // prepend the IV  
  87.                     msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));  
  88.                     msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);  
  89.                     using (CryptoStream csEncrypt =   
  90.                        new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))  
  91.                     {  
  92.                         using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))  
  93.                         {  
  94.                             //Write all data to the stream.  
  95.                             swEncrypt.Write(plainText);  
  96.                         }  
  97.                     }  
  98.                     outStr = Convert.ToBase64String(msEncrypt.ToArray());  
  99.                 }  
  100.             }  
  101.             catch (Exception ex)  
  102.             {  
  103.                 Label l1 = new Label();  
  104.                 l1.ForeColor = Color.Red;  
  105.                 l1.Text = "Enter Proper Key value.";  
  106.                 l1.Show();  
  107.                 Form1 f = new Form1();  
  108.                 f.Controls.Add(l1);  
  109.             }  
  110.             finally  
  111.             {  
  112.                 // Clear the RijndaelManaged object.  
  113.                 if (aesAlg != null)  
  114.                     aesAlg.Clear();  
  115.             }  
  116.   
  117.             // Return the encrypted bytes from the memory stream.  
  118.             return outStr;  
  119.         }  
  120.   
  121.         /// <summary>  
  122.         /// Decrypt the given string.  Assumes the string was encrypted using  
  123.         /// EncryptStringAES(), using an identical sharedSecret.  
  124.         /// </summary>  
  125.         /// <param name="cipherText">The text to decrypt.</param>  
  126.         /// <param name="sharedSecret">A password used to generate a key for decryption.</param>  
  127.         public static string DecryptStringAES(string cipherText, string sharedSecret)  
  128.         {  
  129.             if (string.IsNullOrEmpty(cipherText))  
  130.                 throw new ArgumentNullException("cipherText");  
  131.             if (string.IsNullOrEmpty(sharedSecret))  
  132.                 throw new ArgumentNullException("sharedSecret");  
  133.   
  134.             // Declare the RijndaelManaged object  
  135.             // used to decrypt the data.  
  136.             RijndaelManaged aesAlg = null;  
  137.   
  138.             // Declare the string used to hold  
  139.             // the decrypted text.  
  140.             string plaintext = null;  
  141.   
  142.             try  
  143.             {  
  144.                 // generate the key from the shared secret and the salt  
  145.                 Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);  
  146.   
  147.                 // Create the streams used for decryption.  
  148.                 byte[] bytes = Convert.FromBase64String(cipherText);  
  149.                 using (MemoryStream msDecrypt = new MemoryStream(bytes))  
  150.                 {  
  151.                     // Create a RijndaelManaged object  
  152.                     // with the specified key and IV.  
  153.                     aesAlg = new RijndaelManaged();  
  154.                     aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);  
  155.                     // Get the initialization vector from the encrypted stream  
  156.                     aesAlg.IV = ReadByteArray(msDecrypt);  
  157.                     // Create a decrytor to perform the stream transform.  
  158.                     ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);  
  159.                     using (CryptoStream csDecrypt =   
  160.                         new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))  
  161.                     {  
  162.                         using (StreamReader srDecrypt = new StreamReader(csDecrypt))  
  163.   
  164.                             // Read the decrypted bytes from the decrypting stream  
  165.                             // and place them in a string.  
  166.                             plaintext = srDecrypt.ReadToEnd();  
  167.                     }  
  168.                 }  
  169.             }  
  170.             catch (Exception ex)  
  171.             {  
  172.                 Label l = new Label();  
  173.                 l.ForeColor = Color.Red;  
  174.                 l.Text="Enter Proper Key value.";  
  175.                 l.Show();  
  176.                 Form1 f = new Form1();  
  177.                 f.Controls.Add(l);  
  178.   
  179.             }  
  180.             finally  
  181.             {  
  182.                 // Clear the RijndaelManaged object.  
  183.                 if (aesAlg != null)  
  184.                     aesAlg.Clear();  
  185.             }  
  186.   
  187.             return plaintext;  
  188.         }  
  189.   
  190.         private static byte[] ReadByteArray(Stream s)  
  191.         {  
  192.             byte[] rawLength = new byte[sizeof(int)];  
  193.             if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)  
  194.             {  
  195.                 throw new SystemException("Stream did not contain properly formatted byte array");  
  196.             }  
  197.   
  198.             byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];  
  199.             if (s.Read(buffer, 0, buffer.Length) != buffer.Length)  
  200.             {  
  201.                 throw new SystemException("Did not read byte array properly");  
  202.             }  
  203.   
  204.             return buffer;  
  205.         }  
  206.   
  207.         private void btnCpyEncrt_Click(object sender, EventArgs e)  
  208.         {  
  209.             Clipboard.SetText(txtResult.Text);  
  210.         }  
  211.     }  
  212. }  
The following describes how to use it:
  1. Enter a message into the text field at the bottom.
  2. Enter any unordinary and unique password (and confirm password).
  3. Press the "Encrypt" button.
  4. Select and copy the encrypted code and send it to the respondent. It's safe to send it as an email message.
  5. Inform him about your secret password.
  6. When the recipient has received the encrypted message, he visits this site and decrypts the message into the original form using your secret password.