Cryptography in C# (.NET): Data Encryption and Hashing
Modern applications on the .NET platform almost always require data protection. The System.Security.Cryptography library provides a complete set of tools for implementing cryptographic operations: from symmetric and asymmetric encryption to hashing and digital signature generation. In this article, we will review the main algorithms available in C# and show examples of their use.
1. Main Cryptography Classes in .NET
All cryptographic classes are located in the System.Security.Cryptography namespace. Main categories:
- Symmetric encryption — one key for encryption and decryption (Aes, DES, TripleDES).
- Asymmetric encryption — a pair of keys: public and private (RSA, ECDiffieHellman).
- Hashing — one-way data transformation (SHA256, SHA512, MD5).
- Random number generation — cryptographically secure generator (RandomNumberGenerator).
2. Symmetric Encryption Using AES as an Example
The AES (Advanced Encryption Standard) algorithm is the most common symmetric cipher. To use it in .NET, the Aes class is used.
Example of string encryption and decryption:
using System;using System.IO;using System.Security.Cryptography;using System.Text;
public class AesExample{ public static byte[] EncryptStringToBytes_Aes(string plainText, byte[] key, byte[] iv) { using (Aes aesAlg = Aes.Create()) { aesAlg.Key = key; aesAlg.IV = iv;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(plainText); } return msEncrypt.ToArray(); } } } }
public static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] key, byte[] iv) { using (Aes aesAlg = Aes.Create()) { aesAlg.Key = key; aesAlg.IV = iv;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(cipherText)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { return srDecrypt.ReadToEnd(); } } } } }}Usage:
byte[] key = RandomNumberGenerator.GetBytes(32); // 256-bit keybyte[] iv = RandomNumberGenerator.GetBytes(16); // 128-bit IV
string original = "Secret data";byte[] encrypted = AesExample.EncryptStringToBytes_Aes(original, key, iv);string decrypted = AesExample.DecryptStringFromBytes_Aes(encrypted, key, iv);
Console.WriteLine($"Original: {original}");Console.WriteLine($"Decrypted: {decrypted}");3. Asymmetric Encryption with RSA
RSA is used for secure key exchange or small amounts of data. In .NET, it is implemented by the RSA class.
Example of key generation and encryption:
using System;using System.Security.Cryptography;using System.Text;
public class RsaExample{ public static void Demonstrate