Back to all posts
C#.NETSecurity

How to Generate RSA Encryption Keys – C#

SathishApril 19, 2010
How to Generate RSA Encryption Keys – C#

RSA key generation is the first step in implementing RSA encryption. This tutorial shows how to generate RSA key pairs in C#.

Generating RSA Keys

csharp
using System;
using System.Security.Cryptography;

public class RSAKeyGenerator
{
    public static void GenerateKeys(out string publicKey, out string privateKey)
    {
        using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048))
        {
            publicKey = rsa.ToXmlString(false);  // Public key only
            privateKey = rsa.ToXmlString(true);  // Public and private key
        }
    }
    
    public static void SaveKeysToFile(string publicKeyFile, string privateKeyFile)
    {
        string publicKey, privateKey;
        GenerateKeys(out publicKey, out privateKey);
        
        System.IO.File.WriteAllText(publicKeyFile, publicKey);
        System.IO.File.WriteAllText(privateKeyFile, privateKey);
    }
}

Key Sizes

  • 1024 bits: Minimum recommended (legacy)
  • 2048 bits: Standard security level
  • 4096 bits: High security applications

Best Practices

  • Never share your private key
  • Store private keys securely
  • Use at least 2048-bit keys
  • Consider using certificate stores for production
0claps
Share this post

Comments

Protected by reCAPTCHA v3

No comments yet. Be the first to comment.