You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java RSA加解密问题求助:解密结果恒为1且与加密值不匹配

Hey there, I totally get how frustrating it is when your RSA encryption/decryption isn't working as expected—especially when you keep getting 1 as the decrypted result. Let's break down the common issues that cause this and walk through how to fix them, using typical pitfalls in Java RSA implementations as a guide.

Common Causes & Fixes for RSA Decryption Resulting in 1
  • Incorrect Key Pair Usage
    A super common mistake is mixing up the public and private key's exponent (e and d) or modulus (n) during encryption/decryption. RSA encryption uses the public key (n, e) to compute c = m^e mod n, while decryption needs the private key (n, d) to compute m = c^d mod n. If you accidentally use e instead of d for decryption (or vice versa), or use a mismatched modulus, you'll end up with garbage results—often 1, especially if the exponent is incorrectly set to 1.
    Fix: Double-check your key generation code to ensure you're storing n, e, d correctly, and that encryption uses (n,e) while decryption uses (n,d).

  • Missing or Incorrect Padding
    RSA requires padding (like OAEP or PKCS#1 v1.5) for secure operation. If you're implementing raw RSA (no padding) and your plaintext is larger than the modulus minus required bytes, or if you're not handling padding correctly during decryption, you might end up with invalid results. Raw RSA is also insecure, so never use it in production.
    Fix: Use Java's built-in Cipher class with a proper padding scheme, e.g., Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding") instead of manual BigInteger exponentiation (unless you're explicitly learning the math behind RSA).

  • BigInteger Handling Errors
    When using BigInteger for manual RSA operations:

    • Make sure your plaintext is converted to a BigInteger that's less than the modulus n. If m >= n, m^e mod n will not reverse correctly with ^d mod n, leading to wrong results.
    • Ensure you're using the correct modPow method: encryption is plaintext.modPow(e, n), decryption is ciphertext.modPow(d, n). If you accidentally use mod instead of modPow, or swap the exponent and modulus, you'll get 1 or other garbage values.
      Fix: Add a check that m.compareTo(n) < 0 before encryption, and verify your modPow calls are using the right parameters.
  • Key Generation Issues
    If your key pair is generated incorrectly (e.g., using invalid primes p and q, or miscalculating d as the modular inverse of e modulo φ(n) where φ(n) = (p-1)*(q-1)), the decryption exponent won't reverse the encryption. A common mistake here is miscalculating φ(n)—using n-1 instead of (p-1)*(q-1) will make d invalid, leading to decryption always returning 1 or wrong values.
    Fix: Verify your key generation logic step by step:

    1. Generate two distinct large primes p and q.
    2. Compute n = p * q.
    3. Compute phi = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)).
    4. Choose e such that 1 < e < phi and gcd(e, phi) = 1 (the standard value is 65537).
    5. Compute d = e.modInverse(phi)—this is crucial; if e and phi aren't coprime, modInverse will throw an error, but if you skipped checking the gcd, you might end up with an invalid d.
Example Corrected Code Snippet

Here's a simple working example using Java's standard libraries (avoid manual exponentiation unless you're learning the underlying math):

import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;

public class RSAExample {
    public static void main(String[] args) throws Exception {
        // Generate a secure 2048-bit RSA key pair
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048);
        KeyPair keyPair = keyGen.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        // Original message
        String message = "Hello RSA Encryption!";
        byte[] messageBytes = message.getBytes();

        // Encrypt with public key
        Cipher encryptCipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
        encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = encryptCipher.doFinal(messageBytes);
        String encryptedBase64 = Base64.getEncoder().encodeToString(encryptedBytes);
        System.out.println("Encrypted: " + encryptedBase64);

        // Decrypt with private key
        Cipher decryptCipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
        decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = decryptCipher.doFinal(Base64.getDecoder().decode(encryptedBase64));
        String decryptedMessage = new String(decryptedBytes);
        System.out.println("Decrypted: " + decryptedMessage);
    }
}
Final Tips
  • Stick to Java's standard security libraries for production code—they handle edge cases like padding, key size, and error checking correctly.
  • If you're debugging manual RSA code, add debug logs to print n, e, d, plaintext, and ciphertext at each step to verify their values are as expected.
  • Always use a modulus size of at least 2048 bits (4096 bits is recommended for production) to ensure security.

内容的提问来源于stack exchange,提问作者Bretty135

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:21:06