Thursday, December 22, 2022
HomeITMethods to use symmetric and uneven encryption in C#

Methods to use symmetric and uneven encryption in C#


Encryption transforms information right into a kind that may be learn solely by somebody who has a key that permits them to decrypt it. You should use encryption to guard information “at relaxation” (information that resides in an information retailer) or to guard information “in movement” (information that’s being despatched over a community).

This text will study how we are able to work with two kinds of encryption in C#, symmetric encryption and uneven encryption. Symmetric encryption makes use of one key for each encryption and decryption. Uneven encryption makes use of two distinct keys for encryption and decryption.

To work with the code examples supplied on this article, you must have Visible Studio 2022 put in in your system. In case you don’t have already got a replica, you’ll be able to obtain a replica from right here.

Create a .NET Core console software challenge in Visible Studio

First off, let’s create a .NET Core console software challenge in Visible Studio 2022. Assuming Visible Studio 2022 is put in in your system, observe the steps outlined under to create a brand new .NET Core console software challenge.

  1. Launch the Visible Studio 2022 Preview IDE.
  2. Click on on “Create new challenge.”
  3. Within the “Create new challenge” window, choose “Console App (.NET Core)” from the record of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new challenge” window proven subsequent, specify the identify and placement for the brand new challenge.
  6. Click on Subsequent.
  7. Within the “Extra info” window, specify .NET 7 because the .NET model you want to use.
  8. Click on Create.

This can create a brand new .NET 7 console software challenge in Visible Studio 2022. We’ll use this challenge to work with encryption within the subsequent sections of this text.

Symmetric encryption vs. uneven encryption

Encryption is of two varieties: symmetric encryption and uneven encryption. Each symmetric and uneven encryption may also help defend delicate information residing in your information retailer or in transit. C# gives built-in help for symmetric and uneven encryption by way of the System.Safety.Cryptography namespace.

Whereas symmetric encryption makes use of just one key for encrypting and decrypting information, uneven encryption makes use of two keys: a public key used for encrypting the info and a non-public key used for decrypting the info. Symmetric encryption is usually quicker and extra environment friendly, however you could preserve the important thing secret, as a result of anybody with entry to the important thing can decrypt the info. Uneven encryption is slower than symmetric encryption, but it surely’s additionally far more safe as a result of the decryption key shouldn’t be shared. Solely the individual possessing the personal key will be capable of decode the info.

The variations between symmetric and uneven encryption make them appropriate for various use circumstances, as Microsoft factors out right here within the .NET documentation:

Symmetric encryption and uneven encryption are carried out utilizing completely different processes. Symmetric encryption is carried out on streams and is due to this fact helpful to encrypt massive quantities of knowledge. Uneven encryption is carried out on a small variety of bytes and is due to this fact helpful just for small quantities of knowledge.

This explains why symmetric encryption is usually used to guard information despatched over the community (akin to an e-mail) whereas uneven encryption is usually used to guard delicate information akin to social safety numbers, passwords, and bank card numbers.

Within the following sections, we’ll encrypt and decrypt a string utilizing C#, first with symmetric encryption after which with uneven encryption. We’ll use a string as the info in our examples to maintain issues easy.

Implementing symmetric encryption in C#

To implement symmetric encryption, you will have to generate a 256-bit key for encrypting and decrypting information. Symmetric encryption is quicker than uneven encryption however much less safe as a result of you need to use the identical key for encrypting and decrypting information. The receiver makes use of the identical shared secret to decrypt the message after receiving it from the sender. If the secret’s not shared securely, a 3rd get together might use it to decrypt and skim the info.

Within the console software challenge you created earlier, create a static C# class named SymmetricEncryptionDecryptionManager in a file named SymmetricEncryptionDecryptionManager.cs and enter the next code.

 
utilizing System.Safety.Cryptography;
utilizing System.Textual content;
namespace EncryptionDemo
{
    public class SymmetricEncryptionDecryptionManager
    {
        public static string Encrypt(string information, string key)
        {
            byte[] initializationVector = Encoding.ASCII.GetBytes("abcede0123456789");
            utilizing (Aes aes = Aes.Create())
            {
                aes.Key = Encoding.UTF8.GetBytes(key);
                aes.IV = initializationVector;
                var symmetricEncryptor = aes.CreateEncryptor(aes.Key, aes.IV);
                utilizing (var memoryStream = new MemoryStream())
                {
                    utilizing (var cryptoStream = new CryptoStream(memoryStream as Stream,
symmetricEncryptor, CryptoStreamMode.Write))
                    {
                        utilizing (var streamWriter = new StreamWriter(cryptoStream as Stream))
                        {
                            streamWriter.Write(information);
                        }
                        return Convert.ToBase64String(memoryStream.ToArray());
                    }
                }
            }
        }
        public static string Decrypt(string cipherText, string key)
        {
            byte[] initializationVector = Encoding.ASCII.GetBytes("abcede0123456789");
            byte[] buffer = Convert.FromBase64String(cipherText);
            utilizing (Aes aes = Aes.Create())
            {
                aes.Key = Encoding.UTF8.GetBytes(key);
                aes.IV = initializationVector;
                var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
                utilizing (var memoryStream = new MemoryStream(buffer))
                {
                    utilizing (var cryptoStream = new CryptoStream(memoryStream as Stream,
decryptor, CryptoStreamMode.Learn))
                    {
                        utilizing (var streamReader = new StreamReader(cryptoStream as Stream))
                        {
                            return streamReader.ReadToEnd();
                        }
                    }
                }
            }
        }
    }
}

Within the previous code itemizing, discover there are two strategies, Encrypt and Decrypt. The Encrypt technique accepts the info to encrypt and the key key as parameters. It leverages the Superior Encryption Commonplace (AES) algorithm to carry out symmetric information encryption utilizing the key key. The encrypted information is returned within the type of a Base64 string.

The Decrypt technique accepts the encrypted information and the key key as parameters. It converts the cipher textual content to a byte array, which is used to decrypt the info utilizing the key key. The decrypted information is returned as a string.

You should use the next code snippet to encrypt and decrypt information utilizing the Encrypt and Decrypt strategies ofthe SymmetricEncryptionDecryptionManager class.

 
var encryptedText = SymmetricEncryptionDecryptionManager.Encrypt("That is pattern textual content.", key);
Console.WriteLine(encryptedText);
var decryptedText = SymmetricEncryptionDecryptionManager.Decrypt(encryptedText, key);
Console.WriteLine(decryptedText);

Implementing uneven encryption in C#

In uneven encryption, two completely different keys are used to encrypt and decrypt information. The general public secret is used to encrypt, and the personal secret is used to decrypt. You need to have each a public key and a non-public key to implement uneven encryption.

To encrypt information utilizing uneven encryption, you first have to generate a public/personal key pair. You are able to do this utilizing the RSA algorithm as proven under.

 
var rsa = new RSACryptoServiceProvider();
string publicKeyXML = rsa.ToXmlString(false);
string privateKeyXML = rsa.ToXmlString(true);

Upon getting generated the important thing pair, you need to use the general public key to encrypt information.

 
byte[] information = Encoding.UTF8.GetBytes("Howdy world!");
byte[]encryptedData = rsa.Encrypt(information, false);

Then, to decrypt the info, you will have to make use of the personal key.

 
byte[] decryptedData = rsa.Decrypt(encryptedData, false);
string message = Encoding.UTF8.GetString(decryptedData);

Allow us to create a brand new class named AsymmetricEncryptionDecryptionManager with the next code.

 
public class AsymmetricEncryptionDecryptionManager
{
  public static string Encrypt(string information, RSAParameters rsaParameters)
  {
    utilizing(var rsaCryptoServiceProvider = new RSACryptoServiceProvider())
    {
      rsaCryptoServiceProvider.ImportParameters(rsaParameters);
      var byteData = Encoding.UTF8.GetBytes(information);
      var encryptedData = rsaCryptoServiceProvider.Encrypt(byteData, false);
      return Convert.ToBase64String(encryptedData);
    }
  }
  public static string Decrypt(string cipherText, RSAParameters rsaParameters)
  {
    utilizing(var rsaCryptoServiceProvider = new RSACryptoServiceProvider())
    {
      var cipherDataAsByte = Convert.FromBase64String(cipherText);
      rsaCryptoServiceProvider.ImportParameters(rsaParameters);
      var encryptedData = rsaCryptoServiceProvider.Decrypt(cipherDataAsByte, false);
      return Encoding.UTF8.GetString(encryptedData);
    }
  }
}

You should use the next code snippet to encrypt and decrypt information utilizing the Encrypt and Decrypt strategies of the AsymmetricEncryptionDecryptionManager class.

 
var rsaCryptoServiceProvider = new RSACryptoServiceProvider(2048);
var cipherText = AsymmetricEncryptionDecryptionManager.Encrypt("That is pattern textual content.", rsaCryptoServiceProvider.ExportParameters(false));
Console.WriteLine(cipherText);
var plainText = AsymmetricEncryptionDecryptionManager.Decrypt(cipherText, rsaCryptoServiceProvider.ExportParameters(true));
Console.WriteLine(plainText);

Determine 1 under exhibits the output whenever you execute the above program.

symmetric asymmetric encryption IDG

Determine 1. An indication of uneven encryption in .NET.

Observe you could merge each SymmetricEncryptionDecryptionManager and AsymmetricEncryptionDecryptionManager into one class and write overloaded strategies for symmetric and uneven encryption and decryption. You should use this information to construct safe functions or web sites that defend information from unauthorized entry.

Copyright © 2022 IDG Communications, Inc.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments