SSH and OpenSSL: Decrypting RSA Private Keys with ssh-add and openssl pkeyutl

Abstract: Resolve confusion about decrypting RSA keys by clarifying that ssh-add loads unencrypted keys into memory and providing OpenSSL commands to encrypt or remove passphrases from key files.

Created: 2026-09-11 by

You cannot decrypt an RSA private key with openssl pkeyutl because ssh-add does not encrypt keys; it loads unencrypted keys into the SSH agent's memory. To encrypt a PEM file for storage, use openssl rsa -aes256 -in key.pem -out key_encrypted.pem. To remove passphrase protection, use openssl rsa -in key_encrypted.pem -out key_unencrypted.pem.

Understanding SSH Agent Encryption Misconceptions

A common source of confusion arises when users attempt to manipulate private keys using OpenSSL commands after interacting with the SSH agent. The core misunderstanding lies in the function of ssh-add. Many assume that adding a key to the agent encrypts the file on disk or transforms it into a binary blob that requires decryption later. This is technically incorrect. When you run ssh-add ~/.ssh/id_rsa, the SSH client reads your private key from the filesystem. If the key is protected by a passphrase, the user must enter it interactively. Once verified, the decrypted private key material is loaded into the memory of the running ssh-agent process. The original file on disk remains unchanged. It retains its original format (PEM or OpenSSH) and its original encryption status. The SSH agent holds the decrypted key in RAM to facilitate authentication for subsequent SSH connections without requiring repeated passphrase entry. It does not create a new encrypted version of the key file. Therefore, there is no "encrypted payload" generated by ssh-add that can be passed to openssl pkeyutl for decryption. Attempting to treat the output of ssh-add or the agent's internal state as an encrypted file leads to errors because the data structures are incompatible with standard OpenSSL decryption routines. If your goal is to manage key encryption at rest (on the disk), you must use OpenSSL directly on the key file itself, independent of the SSH agent. The SSH agent operates on decrypted keys in memory, while OpenSSL operates on encrypted files on disk. These are two distinct layers of security management. For more information on resolving connection issues that might arise during key management, see our guide on Troubleshooting kex_exchange_identification Error in Linux SSH Connection.

Encrypting an Unprotected Private Key

To add password protection to an existing unencrypted RSA private key, you should use the openssl rsa command with a specific cipher algorithm. This process converts a plain-text key file into an encrypted PEM file. First, ensure you have a backup of your original key. Never overwrite the only copy of a critical private key until you have verified the new encrypted version works. Use the following command to encrypt the key using AES-256:
openssl rsa -aes256 -in id_rsa -out id_rsa_encrypted
You will be prompted to enter a pass phrase twice. This pass phrase will be required every time you load this specific key file into the SSH agent or use it for manual operations. The resulting id_rsa_encrypted file contains the same key material but wrapped in an encrypted structure defined by the PKCS#1 standard. It is important to note that ssh-add can still read this newly encrypted file. When you run ssh-add id_rsa_encrypted, the SSH agent will prompt you for the passphrase you just created. Upon successful entry, the agent loads the decrypted key into memory, just as it would with any other key.

Removing Passphrase Protection from an Encrypted Key

Conversely, if you wish to remove the passphrase from an encrypted key—perhaps to automate scripts that cannot handle interactive prompts—you can use OpenSSL to strip the encryption. This results in an unencrypted key file. Be aware that storing unencrypted private keys poses a significant security risk. Anyone who gains access to the file can impersonate you. Only perform this step if necessary and ensure strict file permissions are set afterward. Run the following command:
openssl rsa -in id_rsa_encrypted -out id_rsa_unencrypted
You will be prompted for the current passphrase protecting the encrypted file. After verification, OpenSSL writes the decrypted key material to id_rsa_unencrypted without any additional encryption layer. The resulting file can be used by ssh-add without prompting for a password, assuming the file permissions allow the user to read it.

Setting File Permissions

Regardless of whether the key is encrypted or not, Linux systems require strict permissions on private key files. If permissions are too open, SSH clients will refuse to use the key. After creating or modifying your key file, apply these permissions:
  • Owner Read/Write: chmod 600 id_rsa
  • No Group/Other Access: Ensures only the owner can read the key.
If you encounter permission denied errors when trying to use keys, check Permission denied when trying to SSH into CISCO virtual router for detailed troubleshooting steps regarding access rights.

Creating Handy Aliases

Frequently encrypting and decrypting keys can become tedious. You can streamline this workflow by creating shell aliases in your ~/.bashrc or ~/.zshrc file. Add the following lines to your configuration file to create shortcuts:
# Encrypt a key with AES-256
alias ssh-key-encrypt='openssl rsa -aes256 -in $1 -out ${1}_enc'

# Decrypt a key (remove passphrase)
alias ssh-key-decrypt='openssl rsa -in $1 -out ${1%_enc}'
These aliases accept the input filename as an argument. For example, running ssh-key-encrypt id_rsa will generate id_rsa_enc. Running ssh-key-decrypt id_rsa_enc will generate id_rsa. Remember that these aliases operate on local files. They do not interact with the SSH agent's memory. The agent still needs to be started (eval $(ssh-agent)) and populated (ssh-add) separately.

Verifying Key Integrity

After encrypting or decrypting, verify the key is valid by attempting to list its details:
openssl rsa -in id_rsa_encrypted -check -noout
This command checks the private key against its public counterpart embedded within the file. If the key is valid, it returns success. If there is corruption or mismatch, it will report an error. This step is crucial before uploading keys to servers or adding them to agents. For issues related to closing connections after key changes, refer to Closing SSH Connection with Keygen.

Frequently Asked Questions

Can I recover a lost passphrase for my SSH key?

No, you cannot recover a lost passphrase for an SSH private key. The encryption used (typically AES-256) is designed to be computationally infeasible to break without the key. If you forget the passphrase, the key material is effectively lost forever. You must generate a new key pair and update all authorized hosts with the new public key.

Does ssh-add store the key permanently on disk?

No, ssh-add stores the decrypted key only in the memory of the ssh-agent process. It does not write the key back to the filesystem in any form. When the ssh-agent process terminates, the key is removed from memory. To persist the agent across sessions, you typically configure your desktop environment or shell startup scripts to launch the agent automatically.

Why does openssl pkeyutl fail when I try to decrypt my SSH key?

openssl pkeyutl expects an encrypted data payload using specific padding schemes like PKCS#1 OAEP. SSH private keys use a different structure (PKCS#1 or PKCS#8). Furthermore, since ssh-add does not produce an encrypted file, there is nothing for pkeyutl to decrypt. Use openssl rsa for key-specific encryption and decryption tasks instead.

Is it safe to keep unencrypted SSH keys on my system?

It is generally unsafe to leave unencrypted private keys on disk unless they are strictly protected by file permissions (chmod 600) and the system itself is secured against unauthorized access. If someone gains root access or physical access to the machine, they can copy the unencrypted key and use it to authenticate as you. Encrypting the key adds a layer of defense even if the file is stolen.

How do I switch between multiple encrypted keys in the SSH agent?

The SSH agent can hold multiple keys simultaneously. When you connect to a server, the agent offers all loaded keys. If the server accepts one, the connection proceeds. If not, it tries the next. You do not need to decrypt or re-encrypt keys to switch contexts. Simply ensure all relevant encrypted keys are added to the agent using ssh-add, and provide their respective passphrases when prompted.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More