一次不能使用超过128个字节的RSA加密解密。您必须拆分数据并在循环中进行处理,几乎可以随时将字节写入String /
Array。如果您唯一的问题是数据大小,那么您可能没有更多的选择了。只是拆分数据。
一个很好的例子,可能对您来说更完整,它处理的字符串大于128字节:
http :
//coding.westreicher.org/?p=23
一般而言,如果您需要有关RSA加密的更多说明:
以下代码演示了如何使用KeyPairGenerator在Java中生成RSA密钥对:
// Get an instance of the RSA key generatorKeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");// Generate the keys — might take sometime on slow computersKeyPair myPair = kpg.generateKeyPair();这将为您提供一个KeyPair对象,该对象拥有两个键:一个私有和一个公共。为了利用这些密钥,您将需要创建一个Cipher对象,该对象将与SealedObject结合使用以加密将要在网络上终止的数据。这是您的操作方式:
// Get an instance of the Cipher for RSA encryption/decryptionCipher c = Cipher.getInstance("RSA");// Initiate the Cipher, telling it that it is going to Encrypt, giving it the public keyc.init(Cipher.ENCRYPT_MODE, myPair.getPublic());初始化密码后,我们就可以加密数据了。由于在加密之后,如果您看到的是“裸露”的结果数据就没有多大意义,因此我们必须将它们封装在另一个Object中。Java通过SealedObject类提供了此功能。SealedObjects是用于加密对象的容器,这些对象借助Cipher对象加密和解密其内容。
以下示例显示如何创建和加密SealedObject的内容:
// Create a secret messageString myMessage = new String("Secret Message");// Encrypt that message using a new SealedObject and the Cipher we created beforeSealedObject myEncryptedMessage= new SealedObject( myMessage, c);由于生成的对象是经过加密的,因此可以毫无问题地通过网络发送。唯一可以解密并获取数据的人就是拥有私钥的人。通常,这应该是服务器。为了解密消息,我们需要重新初始化Cipher对象,但是这次以不同的模式解密并使用私钥而不是公钥。
这是您在Java中的操作方式:
// Get an instance of the Cipher for RSA encryption/decryptionCipher dec = Cipher.getInstance("RSA");// Initiate the Cipher, telling it that it is going to Decrypt, giving it the private keydec.init(Cipher.DECRYPT_MODE, myPair.getPrivate());现在密码已准备好解密,我们必须告诉SealedObject解密所保存的数据。
// Tell the SealedObject we created before to decrypt the data and return itString message = (String) myEncryptedMessage.getObject(dec);System.out.println("foo = "+message);使用getObject方法时要当心,因为它返回一个Object的实例(即使它实际上是String的一个实例),而不是加密之前的Class的实例,所以您必须将其强制转换为它的事先表格。
以上内容来自:http : //andreas.louca.org/2008/03/20/java-rsa-encryption-an-
example/



