Click here to Skip to main content
15,891,184 members
Articles / Programming Languages / C#

Encrypt and Decrypt Text with a Specified Key

Rate me:
Please Sign up or sign in to vote.
3.15/5 (9 votes)
4 Mar 2013CPOL 70.9K   5.2K   29   7
This software allows you to encrypt and decrypt text with a specified key.
Image 1

Introduction

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

Background

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

Using the Code

Use these namespaces in your code:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security.Cryptography;

Use this code for encrypting and decrypting text:

C#
namespace Encrypter
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        string key, EnValue;

        private void Form1_Load(object sender, EventArgs e)
        {
            txtKey.Text = "o7x8y6";
        }

        private void btnEncrypt_Click(object sender, EventArgs e)
         {
            key = Convert.ToString(txtKey.Text);
            EnValue = Convert.ToString(txtToEncript.Text);

            if (key != "" && EnValue!="" )
            {
                txtResult.Text=EncryptStringAES(EnValue, key);
            }
            else
            {
                lblResult.Text = "Enter text to Encrypt";
                return;
            }
        }

        private void btnDecript_Click(object sender, EventArgs e)
        {
               EnValue = Convert.ToString(txtResult.Text);
               key = Convert.ToString(txtKey.Text);

            if (key != "" && EnValue != "")
            {
                txtToEncript.Text = DecryptStringAES(EnValue,key);
            }
            else
            {
                lblResult.Text = "Enter text to Decrypt";
                return;
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private static byte[] _salt = Encoding.ASCII.GetBytes("o6806642kbM7c5");

        /// <summary>
        /// Encrypt the given string using AES.  The string can be decrypted using
        /// DecryptStringAES().  The sharedSecret parameters must match.
        /// </summary>
        /// <param name="plainText">The text to encrypt.</param>
        /// <param name="sharedSecret">A password used to generate a key for encryption.</param>
        public static string EncryptStringAES(string plainText, string sharedSecret)
        {
            if (string.IsNullOrEmpty(plainText))
                throw new ArgumentNullException("plainText");
            if (string.IsNullOrEmpty(sharedSecret))
                throw new ArgumentNullException("sharedSecret");

            string outStr = null;                 // Encrypted string to return
            RijndaelManaged aesAlg = null;        // RijndaelManaged object used to encrypt the data.

            try
            {
                // generate the key from the shared secret and the salt
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

                // Create a RijndaelManaged object
                aesAlg = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

                // Create a decryptor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    // prepend the IV
                    msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                    msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                    using (CryptoStream csEncrypt = 
                       new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                    }
                    outStr = Convert.ToBase64String(msEncrypt.ToArray());
                }
            }
            catch (Exception ex)
            {
                Label l1 = new Label();
                l1.ForeColor = Color.Red;
                l1.Text = "Enter Proper Key value.";
                l1.Show();
                Form1 f = new Form1();
                f.Controls.Add(l1);
            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }

            // Return the encrypted bytes from the memory stream.
            return outStr;
        }

        /// <summary>
        /// Decrypt the given string.  Assumes the string was encrypted using
        /// EncryptStringAES(), using an identical sharedSecret.
        /// </summary>
        /// <param name="cipherText">The text to decrypt.</param>
        /// <param name="sharedSecret">A password used to generate a key for decryption.</param>
        public static string DecryptStringAES(string cipherText, string sharedSecret)
        {
            if (string.IsNullOrEmpty(cipherText))
                throw new ArgumentNullException("cipherText");
            if (string.IsNullOrEmpty(sharedSecret))
                throw new ArgumentNullException("sharedSecret");

            // Declare the RijndaelManaged object
            // used to decrypt the data.
            RijndaelManaged aesAlg = null;

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            try
            {
                // generate the key from the shared secret and the salt
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

                // Create the streams used for decryption.
                byte[] bytes = Convert.FromBase64String(cipherText);
                using (MemoryStream msDecrypt = new MemoryStream(bytes))
                {
                    // Create a RijndaelManaged object
                    // with the specified key and IV.
                    aesAlg = new RijndaelManaged();
                    aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                    // Get the initialization vector from the encrypted stream
                    aesAlg.IV = ReadByteArray(msDecrypt);
                    // Create a decrytor to perform the stream transform.
                    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                    using (CryptoStream csDecrypt = 
                        new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                Label l = new Label();
                l.ForeColor = Color.Red;
                l.Text="Enter Proper Key value.";
                l.Show();
                Form1 f = new Form1();
                f.Controls.Add(l);

            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }

            return plaintext;
        }

        private static byte[] ReadByteArray(Stream s)
        {
            byte[] rawLength = new byte[sizeof(int)];
            if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
            {
                throw new SystemException("Stream did not contain properly formatted byte array");
            }

            byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
            if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
            {
                throw new SystemException("Did not read byte array properly");
            }

            return buffer;
        }

        private void btnCpyEncrt_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(txtResult.Text);
        }
    }
}

How to Use this Service

  1. Enter message in the text field at the bottom.
  2. Enter any unordinary and unique password (and confirm password).
  3. Press 'Encrypt' button.
  4. Select and copy encrypted code and send it to respondent. It's safe to send it as an email message.
  5. Inform him about your secret password.
  6. When recipient has received encrypted message, he visits this site and decrypts message to original form using your secret password.

History

  • 4th March, 2013: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
Hi!!! I am Shubham Choudhary
I consider myself an enthusiastic programmer, but I simply don't have time to code in my spare time. I have a life besides coding, also! And when I code in my free time, I am mostly hired for it as well. But I do read lots of articles and books in my free time.

Comments and Discussions

 
QuestionGood !! Pin
kifle feleke8-Mar-22 21:13
kifle feleke8-Mar-22 21:13 
QuestionMessage Closed Pin
8-Mar-22 20:50
kifle feleke8-Mar-22 20:50 
Questionthank you Pin
Member 1264939724-Dec-16 13:54
Member 1264939724-Dec-16 13:54 
Questiongood Pin
Member 1118043516-Apr-16 20:46
Member 1118043516-Apr-16 20:46 
Questiondoubt Pin
Member 1048501826-Dec-13 20:24
Member 1048501826-Dec-13 20:24 
GeneralMy vote of 4 Pin
Amir Mohammad Nasrollahi29-Jul-13 0:35
professionalAmir Mohammad Nasrollahi29-Jul-13 0:35 
GeneralMy vote of 5 Pin
Shubh Agrahari6-Mar-13 19:57
Shubh Agrahari6-Mar-13 19:57 
GeneralRe: My vote of 5 Pin
Shubham Choudhary19-Mar-13 20:27
Shubham Choudhary19-Mar-13 20:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.