C# Class Encrypter System Security Cryptography C# Code Library

We need a class that allows us to encrypt and decrypt information. This class will be good for us to have it to incorporate into our projects. Typically used to encrypt data in a database and then decrypt it. For example addresses, passwords.

In this C# Class we are going to use the Asp.net System Security Cryptography Assembly. For them we need to develop two functions:

  • Encrypt Function: It will return the encrypted value
  • Decrypt Function: It will return the decrypted value

Exploring the System.Security.Cryptography assembly in C#

The System.Security.Cryptography assembly in C# provides a comprehensive set of cryptographic algorithms and services for securing data in transit and at rest. This assembly includes implementations for a wide range of cryptographic algorithms such as Advanced Encryption Standard (AES), Data Encryption Standard (DES), and RSA encryption. It also includes classes for generating secure random numbers and hashing functions for password storage and verification. This assembly is an essential component of any C# application that requires robust security features.


Encryption can be used to protect sensitive data such as passwords, credit card numbers, personal identification information, and other confidential information. It can also be used to secure communication between two parties, such as in the case of email or instant messaging. Encryption ensures that only authorized parties have access to the information, and helps to prevent data breaches and cyber attacks.


Strategy to follow to develop the C# Encryption Class

  1. Create a class called "Encrypter"
  2. Create a function that encrypts the information you provide through two parameters: text to encrypt and encryption phrase
  3. Create a function that decrypts the information it provides through two parameters: text to decrypt and decryption phrase

Let's start

1. Creating the "Encrypter" Class

Create a public C# Class called "Encrypter"

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
class Encrypter
{

}

2. Creating the C# Encrypter Function

Create a public C# function called "Encrypt" inside the "Encrypter" Class

public static string Encrypt(string textoencrypt, String pass)
{
    try
    {
        string EncryptionKey = pass;
        byte[] clearBytes = Encoding.Unicode.GetBytes(textoencrypt);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = 
            	new Rfc2898DeriveBytes(EncryptionKey,
                new byte[] { 0x49, 0x76, 0x61, 0x6E, 0x20,
                            0x4D, 0x65, 0x64, 0x76, 0x65, 0x64, 
                            0x65, 0x76 });

            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms,
                    encryptor.CreateEncryptor(), 
                    CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                textoencrypt = Convert.ToBase64String(ms.ToArray());
            }
        }
        return textoencrypt;
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
}

3. Creating the C# Decrypter Function

Create a public C# function called "Decrypt" inside the "Decrypter" Class

public static string Decrypt(string textodecrypt, string pass)
{
    try
    {
        string EncryptionKey = pass;
        if (textodecrypt != null)
            textodecrypt = textodecrypt.Replace(" ", "+");
        byte[] cipherBytes = Convert.FromBase64String(textodecrypt);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb =
                new Rfc2898DeriveBytes(EncryptionKey,
                new byte[] { 0x49, 0x76, 0x61, 0x6E, 0x20,
                            0x4D, 0x65, 0x64, 0x76, 0x65, 0x64, 
                            0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms,
                    encryptor.CreateDecryptor(), 
                    CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                textodecrypt =
                    Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return textodecrypt;
    }
    catch (Exception)
    {
        return "... Incorrect Phrase!";
    }
}

C# Code Class Encrypter with Asp.Net System Security Cryptography Assembly

Here is the complete structure for the C# Encrypter class using Asp.Net System Security Cryptography Assembly
Here's an example of a C# encryption class that can be used to encrypt sensitive data such as passwords, credit card numbers, and other confidential information. The class uses the Advanced Encryption Standard (AES) algorithm for encryption and the Base64 encoding for conversion to a string. The key and initialization vector (IV) are generated using the RNGCryptoServiceProvider class to ensure secure key generation.

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
class Encrypter
{
    //Encrypt
    public static string Encrypt(string textoencrypt, String pass)
    {
        try
        {
            string EncryptionKey = pass;
            byte[] clearBytes = Encoding.Unicode.GetBytes(textoencrypt);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = 
                	new Rfc2898DeriveBytes(EncryptionKey,
                    new byte[] { 0x49, 0x76, 0x61, 0x6E, 0x20,
                            0x4D, 0x65, 0x64, 0x76, 0x65, 0x64, 
                            0x65, 0x76 });

                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms,
                        encryptor.CreateEncryptor(), 
                        CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    textoencrypt = Convert.ToBase64String(ms.ToArray());
                }
            }
            
            return textoencrypt;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

    //Decrypt
    public static string Decrypt(string textodecrypt, string pass)
    {
        try
        {
            string EncryptionKey = pass;
            if (textodecrypt != null)
                textodecrypt = textodecrypt.Replace(" ", "+");
            byte[] cipherBytes = Convert.FromBase64String(textodecrypt);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb =
                    new Rfc2898DeriveBytes(EncryptionKey,
                    new byte[] { 0x49, 0x76, 0x61, 0x6E, 0x20,
                            0x4D, 0x65, 0x64, 0x76, 0x65, 0x64, 
                            0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms,
                        encryptor.CreateDecryptor(), 
                        CryptoStreamMode.Write))
                    {
                        cs.Write(cipherBytes, 0, cipherBytes.Length);
                        cs.Close();
                    }
                    
                    textodecrypt =
                        Encoding.Unicode.GetString(ms.ToArray());
                }
            }
            return textodecrypt;
        }
        catch (Exception)
        {
            return "... Incorrect Phrase!";
        }
    }
}

Running the C# Encrypter class

Below is the C# program Running the C# Encryption Class

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

namespace ConsoleApp2
{
    class Encrypter
    {
        //Encrypt
        public static string Encrypt(string textoencrypt, 
        							string pass)
        {
            try
            {
                string EncryptionKey = pass;
                byte[] clearBytes = 
                Encoding.Unicode.GetBytes(textoencrypt);
                using (Aes encryptor = Aes.Create())
                {
                    Rfc2898DeriveBytes pdb = 
                    	new Rfc2898DeriveBytes(EncryptionKey,
                        new byte[] { 0x49, 0x76, 0x61, 0x6E, 0x20,
                            0x4D, 0x65, 0x64, 0x76, 0x65, 0x64, 
                            0x65, 0x76 });

                    encryptor.Key = pdb.GetBytes(32);
                    encryptor.IV = pdb.GetBytes(16);
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = 
                        new CryptoStream(ms,
                            encryptor.CreateEncryptor(), 
                            CryptoStreamMode.Write))
                        {
                            cs.Write(clearBytes, 0, 
                            clearBytes.Length);
                            
                            cs.Close();
                        }
                        textoencrypt = 
                        Convert.ToBase64String(ms.ToArray());
                    }
                }
                return textoencrypt;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        //Decrypt
        public static string Decrypt(string textodecrypt, 
        							string pass)
        {
            try
            {
                string EncryptionKey = pass;
                if (textodecrypt != null)
                    textodecrypt = textodecrypt.Replace(" ", "+");
                byte[] cipherBytes = 
                	Convert.FromBase64String(textodecrypt);
                using (Aes encryptor = Aes.Create())
                {
                    Rfc2898DeriveBytes pdb =
                        new Rfc2898DeriveBytes(EncryptionKey,
                        new byte[] { 0x49, 0x76, 0x61, 0x6E, 0x20,
                            0x4D, 0x65, 0x64, 0x76, 0x65, 0x64, 
                            0x65, 0x76 });
                    encryptor.Key = pdb.GetBytes(32);
                    encryptor.IV = pdb.GetBytes(16);
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = 
                        	new CryptoStream(ms,
                            encryptor.CreateDecryptor(), 
                            CryptoStreamMode.Write))
                            
                        {
                            cs.Write(cipherBytes, 0, 
                            cipherBytes.Length);
                            cs.Close();
                        }
                        textodecrypt =
                        Encoding.Unicode.GetString(ms.ToArray());
                    }
                }
                return textodecrypt;
            }
            catch (Exception)
            {
                return "... Incorrect Phrase!";
            }
        }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            bool debug = true;
            string text;
            string pass;

            Console.WriteLine("Enter text for Encrypt:");
            text = Console.ReadLine();
            Console.WriteLine("Enter Phrase:");
            pass = Console.ReadLine();

            //Encrypt
            text = Encrypter.Encrypt(text, pass);
            Console.WriteLine("Text Encrypted: {0}", text);
            Console.WriteLine("");

            //Decrypt
            Console.WriteLine("Enter Phrase to Decrypt:");
            pass = Console.ReadLine();
            string TextDecrypted =
            Encrypter.Decrypt(text, pass);
            Console.WriteLine("Text Decrypted: {0}",
            TextDecrypted);

            if (debug)
                Console.ReadLine();

        }
    }
}

Output 1

Output 2

Juan A. Ripoll - Programming Tutorials and Courses © 2024 All rights reserved.  Legal Conditions.