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.
RSA is an asymmetric encryption algorithm, meaning it uses two keys:
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).
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.
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.
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.
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.
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;
}
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.
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.
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