C# Program to Encrypt/Decrypt a String using Rijndael Key

This is a C# Program to check whether the entered number is even or odd.

Problem Description

This C# Program Encrypts/Decrypts using Rijndael Key.

Problem Solution

Here the namespace that is used is system.security.cryptography and the methods and properties of the rijndael method is used.

Program/Source Code

Here is source code of the C# Program to Encrypt/Decrypt using Rijndael Key. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Encrypt/Decrypt using Rijndael Key
 */
using System;
using System.IO;
using System.Security.Cryptography;
namespace RijndaelManage
{
    class Rijndael
    {
        public static void Main()
        {
            try
            {
 
                string original = "Data For Encryption!!!!!";
                using (RijndaelManaged myRijndael = new RijndaelManaged())
                {
 
                    myRijndael.GenerateKey();
                    myRijndael.GenerateIV();
                    byte[] encrypted = EncryptStringToBytes(original, 
                                       myRijndael.Key, myRijndael.IV); 
                    string aftdecryp = DecryptStringFromBytes(encrypted, 
                                       myRijndael.Key, myRijndael.IV);
                    Console.WriteLine("Original:   {0}", original);
                    Console.WriteLine("After Decryption: {0}", aftdecryp);
                }
 
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
            }
        }
        static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
        {
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("Key");
            byte[] encrypted; 
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.Key = Key;
                rijAlg.IV = IV;
                ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, 
                                             rijAlg.IV); 
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, 
                            encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }
            return encrypted;
        }
        static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
        { 
            if (cipherText == null || cipherText.Length <= 0)
                throw new ArgumentNullException("cipherText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("Key"); 
            string plaintext = null; 
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.Key = Key;
                rijAlg.IV = IV;
                ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, 
                                             rijAlg.IV); 
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, 
                           decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
 
            }
 
            return plaintext;
         }
    }
}
Program Explanation

This C# program is used to demonstrate how to generate a persistent (i.e. non-random) symmetric key using the Rijndael and use this key to encrypt and decrypt a text string. The key is derived from several characteristics passed to encryption and decryption routines.

advertisement
advertisement

This class uses a symmetric key algorithm (Rijndael/AES) to encrypt and decrypt data. As long as encryption and decryption routines use the same parameters to generate the keys, the keys are guaranteed to be the same. The class uses static functions with duplicate code to make it easier to demonstrate encryption and decryption logic.

Create a new instance of the Rijndael class. This generates a new key and initialization vector. The GenerateKey() method is used to override, when overridden in a derived class, generates a random key () to use for the algorithm. And Generate() method is used to override, when overridden in a derived class, generates a random initialization vector to use for the algorithm.

Encrypt the string to an array of bytes and decrypt the bytes to a string. Print the original data and the decrypted data. Using if condition statements check an argument. Create a Rijndael object with the specified key and IV.

Note: Join free Sanfoundry classes at Telegram or Youtube

Then decrypt to perform the stream transform and create the streams used for encryption. Using RijndaelManaged write all data to the stream and return the encrypted bytes from the memory stream. Using if condition statements check the arguments.

Declare the string used to hold, and create a Rijndael object with the specified key and IV. Create a decryptor to perform the stream transform and also create the streams used for decryption. Then we are reading the decrypted bytes from the decrypting stream and place them in a string.

Runtime Test Cases
 
Original     : Data for Encryption!!!!!
After Decryption : Data for Encryption!!!!!

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

advertisement
If you wish to look at all C# Programming examples, go to 1000 C# Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.