The System.Security.Cryptography namespace provides classes for encryption, hashing, and signing data. It supports symmetric and asymmetric encryption algorithms, hashing algorithms, and secure random number generation.

Key Concepts

Examples

1. Symmetric Encryption Using AES

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

class AESExample
{
    public static void Main()
    {
        string plainText = "Sensitive data to encrypt";
        using (Aes aes = Aes.Create())
        {
            aes.GenerateKey();
            aes.GenerateIV();

            // Encrypt
            byte[] encrypted = Encrypt(plainText, aes.Key, aes.IV);

            Console.WriteLine("Encrypted: " + Convert.ToBase64String(encrypted));

            // Decrypt
            string decrypted = Decrypt(encrypted, aes.Key, aes.IV);
            Console.WriteLine("Decrypted: " + decrypted);
        }
    }

    public static byte[] Encrypt(string plainText, byte[] key, byte[] iv)
    {
        using (Aes aes = Aes.Create())
        using (ICryptoTransform encryptor = aes.CreateEncryptor(key, iv))
        using (MemoryStream ms = new MemoryStream())
        using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
        {
            byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
            cs.Write(plainBytes, 0, plainBytes.Length);
            cs.FlushFinalBlock();
            return ms.ToArray();
        }
    }

    public static string Decrypt(byte[] cipherText, byte[] key, byte[] iv)
    {
        using (Aes aes = Aes.Create())
        using (ICryptoTransform decryptor = aes.CreateDecryptor(key, iv))
        using (MemoryStream ms = new MemoryStream(cipherText))
        using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
        using (StreamReader sr = new StreamReader(cs))
        {
            return sr.ReadToEnd();
        }
    }
}

2. Hashing Data Using SHA256

using System;
using System.Security.Cryptography;
using System.Text;

class HashingExample
{
    public static void Main()
    {
        string data = "Sensitive data to hash";
        string hash = ComputeHash(data);
        Console.WriteLine("Hash: " + hash);
    }

    public static string ComputeHash(string data)
    {
        using (SHA256 sha256 = SHA256.Create())
        {
            byte[] hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(data));
            return Convert.ToBase64String(hashBytes);
        }
    }
}

3. Asymmetric Encryption Using RSA

using System;
using System.Security.Cryptography;
using System.Text;

class RSAExample
{
    public static void Main()
    {
        string data = "Sensitive data to encrypt";

        using (RSA rsa = RSA.Create())
        {
            // Generate keys
            rsa.KeySize = 2048;
            string publicKey = Convert.ToBase64String(rsa.ExportRSAPublicKey());
            string privateKey = Convert.ToBase64String(rsa.ExportRSAPrivateKey());

            Console.WriteLine("Public Key: " + publicKey);
            Console.WriteLine("Private Key: " + privateKey);

            // Encrypt
            byte[] encrypted = rsa.Encrypt(Encoding.UTF8.GetBytes(data), RSAEncryptionPadding.Pkcs1);
            Console.WriteLine("Encrypted: " + Convert.ToBase64String(encrypted));

            // Decrypt
            byte[] decrypted = rsa.Decrypt(encrypted, RSAEncryptionPadding.Pkcs1);
            Console.WriteLine("Decrypted: " + Encoding.UTF8.GetString(decrypted));
        }
    }
}

4. Data Protection API (DPAPI)

using System;
using System.Security.Cryptography;
using System.Text;

class DPAPIExample
{
    public static void Main()
    {
        string sensitiveData = "Sensitive data to protect";
        byte[] encrypted = Protect(sensitiveData);
        Console.WriteLine("Encrypted: " + Convert.ToBase64String(encrypted));

        string decrypted = Unprotect(encrypted);
        Console.WriteLine("Decrypted: " + decrypted);
    }

    public static byte[] Protect(string data)
    {
        return ProtectedData.Protect(Encoding.UTF8.GetBytes(data), null, DataProtectionScope.CurrentUser);
    }

    public static string Unprotect(byte[] data)
    {
        byte[] decryptedBytes = ProtectedData.Unprotect(data, null, DataProtectionScope.CurrentUser);
        return Encoding.UTF8.GetString(decryptedBytes);
    }
}

Best Practices