Skip to content
uencoder
TUTORIAL

How to Use RSA Encryption

Encrypt and decrypt data using RSA public-key cryptography, including key generation and padding.

Problem

You need to encrypt data with a public key so that only the holder of the private key can decrypt it.

Prerequisites

  • Understanding of public-key cryptography
  • Knowledge of key sizes and padding

Steps

  1. 1. Generate or obtain a key pair

    Generate an RSA key pair of at least 2048 bits; 3072 or 4096 bits are recommended for long-term security. The public key can be shared freely; the private key must be kept secret. Alternatively, obtain the recipient's public key.

    Input
    key size: 4096
    Output
    public key + private key
  2. 2. Encrypt with OAEP padding

    Use OAEP (Optimal Asymmetric Encryption Padding) with a hash like SHA-256. Never use PKCS#1 v1.5 padding for encryption, as it is vulnerable to padding oracle attacks. RSA can only encrypt data smaller than the key size minus padding overhead.

    Input
    small message + public key
    Output
    ciphertext
  3. 3. Decrypt with the private key

    The private key holder decrypts the ciphertext using OAEP with the same hash. For large data, encrypt a symmetric key with RSA and encrypt the data with AES (hybrid encryption). This is how TLS and PGP work.

    Input
    ciphertext + private key
    Output
    original message

Expected result

Data encrypted with a public key that only the corresponding private key can decrypt.

Common errors

Message is too long for RSA
RSA can only encrypt data up to key_size - padding_overhead bytes. Use hybrid encryption: encrypt an AES key with RSA and the data with AES.
Using PKCS#1 v1.5 padding
PKCS#1 v1.5 is vulnerable to Bleichenbacher's padding oracle attack. Always use OAEP.

Troubleshooting

  • If decryption fails, verify the padding scheme and hash match on both sides.
  • For large files, use hybrid encryption rather than chunking with RSA directly.

Security limits

  • RSA key sizes below 2048 bits are considered insecure. Use 3072+ bits for new applications.
  • All operations are local. Private keys never leave your machine.

Related tools

Related tasks

Ready to run it?

References