Cryptography in C# (.NET): Encryption and Hashing
Data security is one of the key challenges in modern development. The .NET platform provides a powerful and flexible set of tools for cryptographic protection in the System.Security.Cryptography namespace. In this article, we will thoroughly examine the main capabilities of cryptography in C#: symmetric and asymmetric encryption, as well as data hashing. The material will be useful for both beginners and experienced developers looking to systematize their knowledge.
1. Main Namespaces and Classes
All cryptographic functionality is concentrated in the System.Security.Cryptography assembly. Key classes:
Aes,DES,TripleDES— symmetric algorithms;RSA,ECDsa,ECDiffieHellman— asymmetric algorithms;SHA256,SHA512,MD5— hashing algorithms;RandomNumberGenerator— cryptographically secure random number generator.
Important: use only modern algorithms. MD5 and SHA1 are considered outdated and insecure for cryptographic purposes.
2. Symmetric Encryption (AES)
Symmetric encryption uses the same key for encryption and decryption. The most popular algorithm is AES (Advanced Encryption Standard). Let's look at an example of encrypting a string.
using System;using System.IO;using System.Security.Cryptography;using System.Text;
public class AesEncryption{ public static byte[] EncryptStringToBytes_Aes(string plainText, byte[] key, byte[] iv) { using (Aes aes = Aes.Create()) { aes.Key = key; aes.IV = iv;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.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 aes = Aes.Create()) { aes.Key = key; aes.IV = iv;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.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(); } } } } }}To generate a secure key and initialization vector (IV), use RandomNumberGenerator:
using System.Security.Cryptography;
byte[] key = new byte[32]; // 256 bitsbyte[] iv = new byte[16]; // 128 bitsusing (RandomNumberGenerator rng = RandomNumberGenerator.Create()){ rng.GetBytes(key); rng.GetBytes(iv);}3. Asymmetric Encryption (RSA)
Asymmetric encryption uses a pair of keys: public and private. RSA is a classic algorithm suitable for encrypting small amounts of data (typically up to 190 bytes for a 2048-bit key). Example:
using System;using System.Security.Cryptography;using System.Text;
public class RsaEncryption{ public static (byte[]