How one can use symmetric and uneven encryption in C# | Rank Tech

roughly How one can use symmetric and uneven encryption in C# will cowl the newest and most present data roughly the world. proper of entry slowly therefore you comprehend with ease and accurately. will addition your information nicely and reliably

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

This text will look at how we will work with two sorts 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 totally different keys for encryption and decryption.

To work with the code samples supplied on this article, you could have Visible Studio 2022 put in in your system. For those who do not have already got a replica, you may obtain a replica from right here.

Create a .NET Core console app venture in Visible Studio

First, let’s create a .NET Core Console App venture in Visible Studio 2022. Assuming Visible Studio 2022 is put in in your system, observe the steps under to create a brand new .NET Core Console App venture. .

  1. Begin the Visible Studio 2022 Preview IDE.
  2. Click on “Create new venture”.
  3. Within the “Create New Undertaking” window, choose “Console App (.NET Core)” from the checklist of templates displayed.
  4. Click on Subsequent.
  5. Within the “Arrange your new venture” window proven under, specify the title and placement of the brand new venture.
  6. Click on Subsequent.
  7. Within the “Extra Info” window, specify .NET 7 because the model of .NET you want to use.
  8. Click on Create.

This can create a brand new .NET 7 Console Software venture in Visible Studio 2022. We’ll use this venture to work with encryption in later sections of this text.

Symmetric vs. Uneven Encryption

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

Whereas symmetric encryption makes use of just one key to encrypt and decrypt knowledge, uneven encryption makes use of two keys: a public key that’s used to encrypt the information, and a non-public key that’s used to decrypt the information. Symmetric encryption is normally sooner and extra environment friendly, however you could hold the important thing secret as a result of anybody with entry to the important thing can decrypt the information. Uneven encryption is slower than symmetric encryption, however it is usually way more safe as a result of the decryption key is just not shared. Solely the one who owns the personal key will have the ability to decrypt the information.

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

Symmetric encryption and uneven encryption are executed utilizing totally different processes. Symmetric encryption is completed in streams and is due to this fact helpful for encrypting giant quantities of information. Uneven encryption is completed on a small variety of bytes and is due to this fact solely helpful for small quantities of information.

This explains why symmetric encryption is usually used to guard knowledge despatched over the community (similar to e-mail), whereas uneven encryption is usually used to guard delicate knowledge similar 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 knowledge in our examples to maintain issues easy.

Implementation of symmetric encryption in C#

To implement symmetric encryption, you have to to generate a 256-bit key to encrypt and decrypt knowledge. Symmetric encryption is quicker than uneven encryption however much less safe as a result of you should use the identical key to encrypt and decrypt knowledge. 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 may use it to decrypt and browse the information.

Within the console app venture that you simply 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 knowledge, 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(knowledge);
                        
                        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 code checklist above, discover that there are two strategies, Encrypt and Decrypt. The Encrypt methodology accepts the information to encrypt and the key key as parameters. Leverages the Superior Encryption Commonplace (AES) algorithm to carry out symmetric knowledge encryption utilizing the key key. The encrypted knowledge is returned as a Base64 string.

The Decrypt methodology accepts the encrypted knowledge and the key key as parameters. Converts the encrypted textual content to a byte array, which is used to decrypt the information utilizing the key key. The decrypted knowledge is returned as a string.

You need to use the next code snippet to encrypt and decrypt knowledge through the use of the Encrypt and Decrypt strategies of the SymmetricEncryptionDecryptionManager class.

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

Uneven encryption implementation in C#

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

To encrypt knowledge utilizing uneven encryption, you could first 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);

As soon as you have generated the important thing pair, you should use the general public key to encrypt the information.

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

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

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

Let’s create a brand new class referred to as AsymmetricEncryptionDecryptionManager with the next code.

 
public class AsymmetricEncryptionDecryptionManager

  public static string Encrypt(string knowledge, RSAParameters rsaParameters)
  
    utilizing(var rsaCryptoServiceProvider = new RSACryptoServiceProvider())
    
      rsaCryptoServiceProvider.ImportParameters(rsaParameters);
      var byteData = Encoding.UTF8.GetBytes(knowledge);
      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 need to use the next code snippet to encrypt and decrypt knowledge 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 if you run the above program.

symmetric asymmetric encryption IDG

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

Word that you would be able to merge SymmetricEncryptionDecryptionManager and AsymmetricEncryptionDecryptionManager into one class and write overloaded strategies for symmetric and uneven encryption and decryption. You need to use this data to construct safe apps or web sites that defend knowledge from unauthorized entry.

Copyright © 2022 IDG Communications, Inc.

I hope the article just about How one can use symmetric and uneven encryption in C# provides notion to you and is helpful for including as much as your information

How to use symmetric and asymmetric encryption in C#

News

Good day Fediverse! Introducing Buffer for Mastodon | Origin Tech

roughly Good day Fediverse! Introducing Buffer for Mastodon will lid the newest and most present instruction roughly the world. entrance slowly appropriately you perceive with out issue and appropriately. will addition your information proficiently and reliably Mastodon is at present going by way of an explosive section of progress. Some folks say it reminds them […]

Read More
News

Samsung T7 Defend 4TB is Now Out there | Summary Tech

roughly Samsung T7 Defend 4TB is Now Out there will cowl the newest and most present counsel regarding the world. learn slowly fittingly you comprehend capably and accurately. will progress your information nicely and reliably Samsung had some thrilling information on the stable state drive (SSD) entrance at present. The corporate introduced the provision of […]

Read More
News

What’s HelloFresh and the way does it work? | Gamer Tech

just about What’s HelloFresh and the way does it work? will lid the newest and most present advice roughly the world. means in slowly thus you comprehend skillfully and accurately. will buildup your data skillfully and reliably Edgar Cervantes / Android Authority Regardless of being one in every of life’s best pleasures, meals will also […]

Read More
x