Generating Symmetric Private Key In C# and .NET

Cryptography functionality in .NET is defined in the System.Security.Cryptography namespace and can be categorized into four major categories – symmetric, asymmetric, digital signature, and hashing.

Symmetric cryptography also known as secret-key encryption is used to encrypt and decrypt data using a single secret key. Same secret key is used to encrypt and decrypt data from both parties, the sender and the receiver.

Major symmetric algorithms are AES, DES, RC2, Rijndael, and TripleDES. Each of these algorithms has a corresponding class in .NET framework, derived from the SymmetricAlgorithm class.

The GenerateKey and GenerateIV methods return the private secret key and initialization vector (IV).

The following code snippet generates a key and IV using TripleDES algorithm.

  1. TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();  
  2. TDES.GenerateIV();  
  3. TDES.GenerateKey();  
Here is a complete code snippet that generates private keys using three different algorithms.

  1. using System;  
  2. using System.Security.Cryptography;  
  3.   
  4. namespace Dig  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             // Generate a symmetric private key using TripleDES algorithm  
  11.             TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();  
  12.             TDES.GenerateIV();  
  13.             TDES.GenerateKey();  
  14.             Console.WriteLine($"TDES Key: {System.Text.Encoding.UTF8.GetString(TDES.Key)}");  
  15.             Console.WriteLine($"TDES IV: {System.Text.Encoding.UTF8.GetString(TDES.IV)}");  
  16.   
  17.             // Generate a symmetric private key using TripleDES algorithm  
  18.             AesCryptoServiceProvider Aes = new AesCryptoServiceProvider();  
  19.             Aes.GenerateIV();  
  20.             Aes.GenerateKey();  
  21.             Console.WriteLine($"Aes Key: {System.Text.Encoding.UTF8.GetString(Aes.Key)}");  
  22.             Console.WriteLine($"Aes IV: {System.Text.Encoding.UTF8.GetString(Aes.IV)}");  
  23.   
  24.             // Generate a symmetric private key using TripleDES algorithm  
  25.             RijndaelManaged rm = new RijndaelManaged();  
  26.             rm.GenerateIV();  
  27.             rm.GenerateKey();  
  28.             Console.WriteLine($"RM Key: {System.Text.Encoding.UTF8.GetString(rm.Key)}");  
  29.             Console.WriteLine($"RM IV: {System.Text.Encoding.UTF8.GetString(rm.IV)}");    
  30.   
  31.             Console.ReadKey();  
  32.         }  
  33.     }  
  34. }  

 


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.