Generating a RSA Key Pair and When to Use Them

Kiran Mohan
2 min readJan 24, 2024

--

Encryption with a Public — Private Key Pair

Introduction

In today’s digital age, secure communication is more important than ever. Whether it’s for personal privacy or safeguarding sensitive business information, ensuring that our communications remain confidential is crucial. This is where the concept of using public and private keys for encryption comes into play.

The Need for Encryption

Imagine you need to send a confidential message or file over the internet. The digital space is like a bustling city with numerous prying eyes and potential interceptors. Sending data without encryption is akin to shouting across a crowded room; anyone can listen in. This is where encryption, specifically using public and private keys, becomes essential.

What are Public and Private Keys?

Public and private keys are part of an encryption technique known as asymmetric cryptography. The public key, which you can share with anyone, is used to encrypt data. The private key, which you keep secret, is used to decrypt that data. This method ensures that only the intended recipient, who possesses the correct private key, can access the information.

Example Use Case

Consider sending an encrypted email. You encrypt the message with the recipient’s public key. Once encrypted, the message can only be decrypted with the corresponding private key, which only the recipient has. This ensures that even if the message is intercepted, it remains unreadable to anyone except the intended recipient.

Generating RSA Public-Private Key Pair

RSA (Rivest–Shamir–Adleman) is a widely used method in public-key cryptography. Here’s how to generate an RSA key pair using command-line tools:

Generating Keys

Generate a Private Key:

Use OpenSSL to create a private key. The following command generates a 2048-bit RSA private key:

openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048

Extract the Public Key:

From the private key, extract the public key using:

openssl rsa -pubout -in private_key.pem -out public_key.pem

This process creates two files: private_key.pem (your private key) and public_key.pem (your public key).

Viewing the Keys

After generating the keys, you can view their contents using the cat command:

View Private Key:

cat private_key.pem

View Public Key:

cat public_key.pem

These commands will display the contents of your private and public keys in the terminal.

Conclusion

Using public and private keys for encryption is a powerful method to secure digital communications. By generating and managing these keys, you can ensure that your sensitive data remains protected from unauthorized access. Remember, the private key should always be kept confidential, as it is the cornerstone of your digital security.

--

--