コンテンツへスキップ
uencoder

RSA 暗号を使う方法

RSA 公開鍵暗号でデータの暗号化・復号を行います。鍵の生成とパディングについても扱います。

问题

公開鍵でデータを暗号化し、秘密鍵の保持者だけが復号できるようにする必要があります。

前提条件

  • 公開鍵暗号の理解
  • 鍵長とパディングに関する知識

ステップ

  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.

    入力
    key size: 4096
    输出
    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.

    入力
    small message + public key
    输出
    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.

    入力
    ciphertext + private key
    输出
    original message

期待される結果

公開鍵で暗号化され、対応する秘密鍵でのみ復号できるデータ。

よくあるエラー

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.

トラブルシューティング指引

  • 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.

セキュリティ上の制限

  • 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.

関連ツール

参考链接