Blog | G5 Cyber Security

Securely Store RSA Keys in .NET

TL;DR

The most secure way to store an RSA key pair in Windows .NET is using the Windows Data Protection API (DPAPI). This encrypts the private key with a key derived from the user’s credentials, making it inaccessible without their login. Avoid storing keys directly in configuration files or unencrypted databases.

Steps to Securely Store RSA Keys

  1. Generate an RSA Key Pair:
using System.Security.Cryptography;

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);
PrivateKey privateKey = rsa.ExportParameters(true);
PublicKey publicKey = rsa.ExportParameters(false);
  • Serialize the Key Pair:
  • using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    
    // Serialize the private key
    using (FileStream stream = new FileStream("privateKey.bin", FileMode.Create))
    {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, privateKey);
    }
    
  • Encrypt with DPAPI:
  • using System.Security;
    
    byte[] encryptedKey = ProtectedData.Protect(
        privateKeyBytes,
        "MyEncryptionSalt", // Entropy - important!
        DataProtectionScope.CurrentUser);
    
  • Store the Encrypted Key:
  • Decrypt with DPAPI:
  • byte[] decryptedKeyBytes = ProtectedData.Unprotect(
        encryptedKey,
        "MyEncryptionSalt", // Must match encryption salt
        DataProtectionScope.CurrentUser);
    
    // Deserialize the private key from the byte array
    RSAParameters decryptedPrivateKey = (RSAParameters)formatter.Deserialize(new MemoryStream(decryptedKeyBytes));
    
  • Important Considerations:
  • Alternatives (Less Secure)

    Exit mobile version