简体   繁体   中英

RSA encryption (modulus/exponent) gives “Message is larger than modulus”

I was trying to encrypt a message using RSA, here is my code:

byte[] message = new byte[] { (byte) 0xbe, (byte) 0xef, (byte) 0xef };
Cipher cipher = Cipher.getInstance("RSA");

KeyFactory keyFactory = KeyFactory.getInstance("RSA");

String mod = "B390F7412F2554387597814A25BC11BFFD95DB2D1456F1B66CDF52BCC1D20C7FF24F3CCE7B2D66E143213F64247454782A377C79C74477A28AF6C317BE68BC6E8FF001D375F9363B5A7161C2DFBC2ED0850697A54421552C6288996AC61AF5A9F7DE218ABBC75A145F891266615EB81D11A22B7260F7608083B373BA4BC0756B";
String exp = "010001";

RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(Hex.fromString(mod)), new BigInteger(Hex.fromString(exp)));
RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);

cipher.init(Cipher.ENCRYPT_MODE, pubKey);

byte[] cipherText = cipher.doFinal(message);
System.out.println("cipher: " + new String(cipherText));

I always get the error:

javax.crypto.BadPaddingException: Message is larger than modulus
    at sun.security.rsa.RSACore.parseMsg(Unknown Source)
    at sun.security.rsa.RSACore.crypt(Unknown Source)
    at sun.security.rsa.RSACore.rsa(Unknown Source)
    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:352)
    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:382)
    at javax.crypto.Cipher.doFinal(Cipher.java:2087)

I also tried with BouncyCastle , but I'm still getting the same error.

Note : Hex.fromString return a byte array of the given Hex String .

And the message is only 3 bytes

Thank you

    byte[] input = new byte[] { (byte) 0xbe, (byte) 0xef , (byte) 0xef};
    Cipher cipher = Cipher.getInstance("RSA");
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    String mod = "B390F7412F2554387597814A25BC11BFFD95DB2D1456F1B66CDF52BCC1D20C7FF24F3CCE7B2D66E143213F64247454782A377C79C74477A28AF6C317BE 68 BC 6E 8F F0 01 D3 75 F9 36 3B 5A 71 61 C2 DF BC 2E D0 85 06 97 A5 44 21 55 2C 62 88 99 6A C6 1A F5 A9 F7 DE 21 8A BB C7 5A 14 5F 89 12 66 61 5E B8 1D 11 A2 2B 72 60 F7 60 80 83 B3 73 BA 4B C0 75 6B".replace(" ", "");
    System.out.println(mod);
    String exp = "010001";
    System.out.println(exp);
    RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(mod, 16), new BigInteger(exp,16));
    RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);
    byte[] cipherText = cipher.doFinal(input);
    System.out.println("cipher: " + new String(cipherText));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM