您一次不能对超过 128 个字节使用 RSA 加密解密。您必须拆分数据并在循环中执行它,几乎随时将字节写入字符串/数组。如果您唯一的问题是数据的大小,那么您可能没有更多工作要做。只是拆分数据。
一个很好的例子,对你来说可能更完整,处理大于 128 字节的字符串:http://www.stellarbuild.com/blog/article/encrypting-and-decrypting-large-data-using-java-and-rsa
如果您需要更多关于 RSA 加密的一般说明:
以下代码演示了如何使用 KeyPairGenerator 在 Java 中生成 RSA 密钥对:
// Get an instance of the RSA key generator
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
// Generate the keys — might take sometime on slow computers
KeyPair myPair = kpg.generateKeyPair();
这将为您提供一个 KeyPair 对象,其中包含两个密钥:一个私有密钥和一个公共密钥。为了使用这些密钥,您需要创建一个 Cipher 对象,该对象将与 SealedObject 结合使用来加密您将通过网络结束的数据。这样做的方法如下:
// Get an instance of the Cipher for RSA encryption/decryption
Cipher c = Cipher.getInstance("RSA");
// Initiate the Cipher, telling it that it is going to Encrypt, giving it the public key
c.init(Cipher.ENCRYPT_MODE, myPair.getPublic());
初始化密码后,我们就可以加密数据了。由于加密后的结果数据如果你看到它们“裸露”将没有多大意义,我们必须将它们封装在另一个对象中。 Java 通过 SealedObject 类提供了这一点。 SealedObjects 是加密对象的容器,它们在 Cipher 对象的帮助下对其内容进行加密和解密。
以下示例显示了如何创建和加密 SealedObject 的内容:
// Create a secret message
String myMessage = new String("Secret Message");
// Encrypt that message using a new SealedObject and the Cipher we created before
SealedObject myEncryptedMessage= new SealedObject( myMessage, c);
生成的对象可以通过网络发送而不必担心,因为它是加密的。唯一可以解密和获取数据的人是持有私钥的人。通常,这应该是服务器。为了解密消息,我们需要重新初始化 Cipher 对象,但这次使用不同的模式,解密并使用私钥而不是公钥。
这就是你在 Java 中的做法:
// Get an instance of the Cipher for RSA encryption/decryption
Cipher dec = Cipher.getInstance("RSA");
// Initiate the Cipher, telling it that it is going to Decrypt, giving it the private key
dec.init(Cipher.DECRYPT_MODE, myPair.getPrivate());
现在 Cipher 已准备好解密,我们必须告诉 SealedObject 解密保存的数据。
// Tell the SealedObject we created before to decrypt the data and return it
String message = (String) myEncryptedMessage.getObject(dec);
System.out.println("foo = "+message);
使用 getObject 方法时要小心,因为它返回一个 Object 的实例(即使它实际上是 String 的一个实例),而不是它在加密之前的 Class 的实例,所以你必须强制转换将其还原为以前的形式。