How to encrypt and decrypt a string in C#? Need easy method with example


How to encrypt and decrypt a string in C#? I would like to know simplest and efficient way for this using some example if possible, thanks


Asked by:- neena
1
: 10891 At:- 6/18/2018 12:57:48 PM
C# encrypt decrypt string







2 Answers
profileImage Answered by:- pika

Here are the working methods with sample output for encryption and decryption of string in C#

Encryption Method in C#

public string Encrypt(string secureUserData , bool useHashing)
{
    byte[] keyArray;
    byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(secureUserData );
    string key = string.Empty;
    byte[] resultArray;
 
      // Get the key from Web.Config file
    //key = ConfigurationManager.AppSettings.Get("EncKey");
    key ="MAKV2SPBNI99212";
     

    if (useHashing)
    {

        MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
        keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
        hashmd5.Clear();

    }
    else
    {
        keyArray = UTF8Encoding.UTF8.GetBytes(key);
    }

    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
    tdes.Key = keyArray;
    tdes.Mode = CipherMode.ECB;
    tdes.Padding = PaddingMode.PKCS7;
 
    ICryptoTransform cTransform = tdes.CreateEncryptor();

    resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

    tdes.Clear();

    return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}

Decryption method in C#

public string Decrypt(string cipherString, bool useHashing)
{
    byte[] keyArray;
    byte[] toEncryptArray = Convert.FromBase64String(cipherString);
    byte[] resultArray;
    string key = string.Empty;

    //key = ConfigurationManager.AppSettings.Get("SecurityKey"); 
    key ="MAKV2SPBNI99212";
 

    if (useHashing)
    {
        MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
        keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
        hashmd5.Clear();
    }
    else
    {
        keyArray = UTF8Encoding.UTF8.GetBytes(key);
    }

    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
    tdes.Key = keyArray;
    tdes.Mode = CipherMode.ECB;
    tdes.Padding = PaddingMode.PKCS7;

 
    ICryptoTransform cTransform = tdes.CreateDecryptor();
    resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);


    tdes.Clear();
 

    return UTF8Encoding.UTF8.GetString(resultArray);

}

Complete C# Console app code for encryption and decryption

using System;
using System.Security.Cryptography;
using System.Text;

namespace EncryptDecryptCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            string UserDataKeyTosecure = "12121";
            //Encrypting data using Hashing
            var cipherString = Encrypt(UserDataKeyTosecure, true);
            Console.WriteLine("Encrypted key : "+ cipherString);

            //Decrypt data using Hashing by passing above cipherString
            var DecryptedKey = Decrypt(cipherString, true);

            Console.WriteLine("Decrypted key : " + DecryptedKey);
        }
        public static string Encrypt(string secureUserData, bool useHashing)
        {
            byte[] keyArray;
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(secureUserData);
            string key = string.Empty;
            byte[] resultArray;

            // Get the key from Web.Config file
            //key = ConfigurationManager.AppSettings.Get("EncKey");
            key = "MAKV2SPBNI99212";


            if (useHashing)
            {

                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                hashmd5.Clear();

            }
            else
            {
                keyArray = UTF8Encoding.UTF8.GetBytes(key);
            }

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateEncryptor();

            resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            tdes.Clear();

            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        public static string Decrypt(string cipherString, bool useHashing)
        {
            byte[] keyArray;
            byte[] toEncryptArray = Convert.FromBase64String(cipherString);
            byte[] resultArray;
            string key = string.Empty;

            //key = ConfigurationManager.AppSettings.Get("SecurityKey"); 
            key = "MAKV2SPBNI99212";


            if (useHashing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                hashmd5.Clear();
            }
            else
            {
                keyArray = UTF8Encoding.UTF8.GetBytes(key);
            }

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;


            ICryptoTransform cTransform = tdes.CreateDecryptor();
            resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);


            tdes.Clear();


            return UTF8Encoding.UTF8.GetString(resultArray);

        }
    }
}

Here is the output of the above Code

encrypt-and-decrypt-a-string-in-csharp-min.png

Hope it helps.

2
At:- 6/21/2018 5:49:09 PM
Thanks 0
By : neena - at :- 7/2/2018 5:38:04 PM


profileImage Answered by:- vikas_jk

Encryption is the process of translating plain text data (plaintext) into something that appears to be random and meaningless (ciphertext).It is used to transform a data into some un-readable form so that authenticated person only can read/access the data. It requires some secret information to transform the plain text to cipher text; it is usually referred as key.

Decryption is the process of converting ciphertext back to plaintext. To encrypt more than a small amount of data, symmetric encryption is used.

Here is the nice article which explains string encryption / decryption in c# with detail.

1
At:- 7/22/2018 6:46:24 PM
Thanks for the useful answer, I see we can implement this string encryption for saving password's also. 0
By : neena - at :- 6/10/2021 8:55:41 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use