Implementing Data Protection and Encryption with System.Security.Cryptography

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

  • Symmetric Encryption: Uses a single key for encryption and decryption. Common algorithms include AES, DES, and TripleDES.
  • Asymmetric Encryption: Asymmetric Encryption uses a public key for encryption and a private key for decryption. Common algorithms include RSA and ECDSA.
  • Hashing: Generates a fixed-size hash value for data. Common algorithms include SHA256, SHA384, and SHA512.
  • Data Protection API (DPAPI): This simplifies encryption and decryption using Protect and Unprotect methods.

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

  • Key Management: Store keys securely using a key management service. Avoid hardcoding keys in your code.
  • Use Strong Algorithms: Use AES for symmetric encryption and RSA with 2048+ bit keys for asymmetric encryption.
  • Secure Data in Transit: Use TLS/SSL for secure communication.
  • Test for Vulnerabilities: Regularly test for cryptographic vulnerabilities.
  • Encrypt Sensitive Data Only: Minimize encryption overhead by encrypting only sensitive parts of the data.

Up Next
    Ebook Download
    View all
    Learn
    View all