java - RSA 加密(模数/指数)给出 "Message is larger than modulus"

标签 java encryption cryptography rsa bouncycastle

我正在尝试使用 RSA 加密消息,这是我的代码:

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));

我总是得到错误:

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)

我也尝试过使用 BouncyCaSTLe,但我仍然遇到同样的错误。

注意:Hex.fromString 返回给定Hex String字节数组

而且消息只有3个字节

谢谢

最佳答案

    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));

关于java - RSA 加密(模数/指数)给出 "Message is larger than modulus",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28049791/

相关文章:

c++ - OpenSSL 区分受信任的 CA 证书和自签名证书

java - 数组中的随机数,其中均值是整数

java - 构建健康指标 spring boot

java - Realm 中的条件 WHERE

c# - 如何检索用于构造 X509AsymmetrySecurityKey 的 X.509 证书?

android - java.io.IOException : Unexpected crypto version 0 异常

Java从子类中获取String

encryption - 如果我包含 openssl,我的开源项目在某些国家/地区是否违法?

c - OpenSSL RSA-2048 未加密 block 比应有的长度长

algorithm - 安全数据加密和验证