Step-by-Step OpenSSL Tutorial: Generating RSA Keys and Encrypting Files
CLI Tutorial📖 8 min read📅 August 4, 2026

Step-by-Step OpenSSL Tutorial: Generating RSA Keys and Encrypting Files

Liam Thorne
Liam Thorne
Workflow Automation Consultant

1. Prerequisites & Environment Check

OpenSSL is pre-installed on macOS and virtually all Linux distributions. Windows users can access it via Git Bash, WSL (Windows Subsystem for Linux), or PowerShell with OpenSSL binaries installed.

openssl version
# Output: OpenSSL 3.0.x or higher

2. Step 1: Generate Private Key

To generate a 2048-bit or 4096-bit RSA private key in modern PKCS#8 format:

# Recommended: Generate 2048-bit key
openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048

# High Security: Generate 4096-bit key
openssl genpkey -algorithm RSA -out private_key_4096.pem -pkeyopt rsa_keygen_bits:4096

3. Step 2: Derive the Public Key

Extract the public key that you can safely share with friends, colleagues, or servers:

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

4. Step 3: Encrypting a Secret File

Create a short text file and encrypt it using the recipient's public key with OAEP padding and SHA-256 (modern standard):

echo "Confidential API Key: DT_SEC_992184" > secret.txt

# Encrypt using pkeyutl
openssl pkeyutl -encrypt -pubin -inkey public_key.pem -in secret.txt -out secret.enc -pkeyopt rsa_padding_mode:oaep -pkeyopt rsa_oaep_md:sha256

5. Step 4: Decrypting the Ciphertext

The recipient uses their private key to decrypt the binary ciphertext back into readable plain text:

openssl pkeyutl -decrypt -inkey private_key.pem -in secret.enc -out decrypted.txt -pkeyopt rsa_padding_mode:oaep -pkeyopt rsa_oaep_md:sha256

cat decrypted.txt
# Output: Confidential API Key: DT_SEC_992184

6. Bonus: Signing and Verifying Hashes

RSA can also prove that a file was authored by you and has not been tampered with in transit:

# Sign a file with private key
openssl dgst -sha256 -sign private_key.pem -out release.sha256.sig software.zip

# Verify signature with public key
openssl dgst -sha256 -verify public_key.pem -signature release.sha256.sig software.zip
# Output: Verified OK
Liam Thorne

Written by Liam Thorne

Liam creates DevOps and terminal automation tutorials, specializing in shell scripts, OpenSSL pipelines, and cloud security.

Share Article

Liam Thorne

Liam Thorne

Workflow Automation Consultant

Liam creates DevOps and terminal automation tutorials, specializing in shell scripts, OpenSSL pipelines, and cloud security.

Article Details

📅 PublishedAugust 4, 2026
⏱️ Read Time8 min read
📂 CategoryCLI Tutorial
#opensslrsatutor#opensslgenrsa#opensslpkeyutle#encryptfilewith#decryptfileopen#digitalsignatur

Loading Related Code Tools...