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.
- TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();
- TDES.GenerateIV();
- TDES.GenerateKey();
Here is a complete code snippet that generates private keys using three different algorithms.
- using System;
- using System.Security.Cryptography;
-
- namespace Dig
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();
- TDES.GenerateIV();
- TDES.GenerateKey();
- Console.WriteLine($"TDES Key: {System.Text.Encoding.UTF8.GetString(TDES.Key)}");
- Console.WriteLine($"TDES IV: {System.Text.Encoding.UTF8.GetString(TDES.IV)}");
-
-
- AesCryptoServiceProvider Aes = new AesCryptoServiceProvider();
- Aes.GenerateIV();
- Aes.GenerateKey();
- Console.WriteLine($"Aes Key: {System.Text.Encoding.UTF8.GetString(Aes.Key)}");
- Console.WriteLine($"Aes IV: {System.Text.Encoding.UTF8.GetString(Aes.IV)}");
-
-
- RijndaelManaged rm = new RijndaelManaged();
- rm.GenerateIV();
- rm.GenerateKey();
- Console.WriteLine($"RM Key: {System.Text.Encoding.UTF8.GetString(rm.Key)}");
- Console.WriteLine($"RM IV: {System.Text.Encoding.UTF8.GetString(rm.IV)}");
-
- Console.ReadKey();
- }
- }
- }