How to Generate RSA Key Pair in Python and Other Popular Programming Languages

Author:
Zeeshan Ahmed
Publish Date:
October 16, 2025

Introduction

Public-key cryptography is the heart of modern data security - from encrypting messages to verifying digital signatures. One of the most common algorithms for asymmetric encryption is RSA (Rivest-Shamir-Adleman).

in this guide, we'll walk through how to generate RSA key pairs (public and private keys) in Python and other popular programming languages like JavaScript, C#, Java, and C++.

You'll see practical, working code snippet for each language - and if you just need a quick RSA key pair right now, you can instantly generate one using DevGizmo's RSA Key Generator.

What Is an RSA Key Pair?

RSA is an asymmetric encryption algorithm, meaning it uses two keys:

  • A public key to encrypt data or verify signatures
  • A private key to decrypt data or create digital signatures

Each key is mathematically linked, but the private key cannot be feasibly derived from the public one - that's what makes RSA secure.

Typical key lengths: 2048 bits (standard), 4096 bits (high security).

Generating RSA Key Pairs in Python

Python's cryptography library provides an easy and secure way to generate RSA keys.

Install the library:

pip install cryptography

Example - Generate RSA Key Pair (2048 bits)

from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization

# Generate private key
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
)

# Get public key
public_key = private_key.public_key()

# Save private key to PEM file
pem_private = private_key.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.PKCS8,
    encryption_algorithm=serialization.NoEncryption()
)
with open("private_key.pem", "wb") as f:
    f.write(pem_private)

# Save public key to PEM file
pem_public = public_key.public_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PublicFormat.SubjectPublicKeyInfo
)
with open("public_key.pem", "wb") as f:
    f.write(pem_public)

Output:

Two PEM-formatted files:

  • private_key.pem
  • public_key.pem

These can be used for signing, encryption, or API authentication.

Generating RSA Key Pairs in JavaScript (Node.js)

In modern Node.js, the built-in crypto module can generate RSA keys easily.

Example - Using Node.js crypto.generateKeyPairSync

const { generateKeyPairSync } = require('crypto');

const { publicKey, privateKey } = generateKeyPairSync('rsa', {
  modulusLength: 2048,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem'
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem'
  }
});

console.log(privateKey);
console.log(publicKey);

Output:

PEM-formatted keys printed to console or saved to files.

You can also use asynchronous version generateKeyPair() for non-blocking operations in large applications.

Generating RSA Keys in C# (.NET)

C#'s System.Security.Cryptography namespace provides built-in support.

Example - Generate 2048-bit RSA Key Pair

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

class Program
{
    static void Main()
    {
        using (RSA rsa = RSA.Create(2048))
        {
            // Export keys to PEM
            string publicKey = Convert.ToBase64String(rsa.ExportRSAPublicKey());
            string privateKey = Convert.ToBase64String(rsa.ExportRSAPrivateKey());

            Console.WriteLine("Public Key:\n" + publicKey);
            Console.WriteLine("\nPrivate Key:\n" + privateKey);
        }
    }
}

For readable PEM formatting, you can use:

File.WriteAllText("public.pem", rsa.ExportRSAPublicKeyPem());
File.WriteAllText("private.pem", rsa.ExportRSAPrivateKeyPem());

.NET 5+ introduced direct methods like ExportRSAPublicKeyPem() - simple and secure.

Generating RSA Keys in Java

Java's KeyPairGenerator class in the java.security package handles RSA keys natively.

Example - Generate RSA key Pair

import java.security.*;
import java.util.Base64;

public class RSAKeyGenExample {
    public static void main(String[] args) throws Exception {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048);

        KeyPair pair = keyGen.generateKeyPair();
        PrivateKey privateKey = pair.getPrivate();
        PublicKey publicKey = pair.getPublic();

        System.out.println("Private Key:\n" +
            Base64.getEncoder().encodeToString(privateKey.getEncoded()));
        System.out.println("\nPublic Key:\n" +
            Base64.getEncoder().encodeToString(publicKey.getEncoded()));
    }
}

Output:

Base64-encoded key data that can be saved or converted into PEM format.

Generating RSA Keys in C++ (Using OpenSSL)

C++ doesn't have built-in cryptography, so the OpenSSL library is widely used.

Example - Generating Keys Using OpenSSL CLI

# Generate private key (2048 bits)
openssl genrsa -out private.pem 2048

# Extract public key
openssl rsa -in private.pem -pubout -out public.pem

Example - Programmatically Using OpenSSL C++ API

#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/bio.h>
#include <iostream>

int main() {
    int bits = 2048;
    unsigned long e = RSA_F4;
    RSA *rsa = RSA_generate_key(bits, e, NULL, NULL);

    BIO *pri = BIO_new_file("private.pem", "w+");
    PEM_write_bio_RSAPrivateKey(pri, rsa, NULL, NULL, 0, NULL, NULL);

    BIO *pub = BIO_new_file("public.pem", "w+");
    PEM_write_bio_RSAPublicKey(pub, rsa);

    RSA_free(rsa);
    BIO_free_all(pub);
    BIO_free_all(pri);

    std::cout << "RSA Key Pair Generated!" << std::endl;
}

Best Practices for RSA Key Management

  • Use at least 2048-bit keys for standard applications; 4096 bits for higher security.
  • Store private keys securely — never commit them to source control.
  • Rotate keys periodically, especially for API or JWT signing.
  • Use PEM or DER formats for interoperability between systems.
  • If possible, handle private keys via a Key Management Service (KMS) like AWS KMS or Azure Key Vault.

Try it Instantly with DevGizmo

Don't want to install libraries or run OpenSSL?

You can generate secure RSA public/private key pairs instantly using DevGizmo's RSA Key Generator

It's free, client-side, an dproduces valid PEM-formatted keys ready for encryption, signing, testing, or certificate creation.

Conclusion

RSA remains one of the cornerstones of digital security. Whether you're working in Python, JavaScript, C#, Java, or C++, you can generate RSA key pairs with just a few lines of code.

Use the right key size, store your private keys safely, and you'll have the foundation for secure communication, data integrity, and encryption.

Need keys right now?

Head over to DevGizmo's RSA Key Generator and create your own instantly.

Summary

Learn how to generate RSA public and private key pairs in Python, JavaScript, C#, Java, and C++. This step-by-step guide includes code examples for each language and explains best practices for secure key management. Whether you're building encryption systems, digital signatures, or authentication tools, create secure RSA keys easily - or try DevGizmo's online RSA Key Generator

Like this post? Explore more tools built for developers