Mah*_*uri 17 java encryption rsa
我正在尝试实施PKI.我想在java中使用RSA加密大字符串而不使用充气城堡.我得到的问题是数据不能超过117个字节.我试图找到我失败的解决方案.我是这个加密的新手.请以大字符串为例帮我解释一下.
msj*_*121 32
您不能一次使用超过大约128个字节的RSA加密解密.你必须拆分数据并在一个循环中完成,然后将字节写入String/Array.如果你唯一的问题是数据的大小,你可能没有更多的东西可去.只需拆分数据.
一个很好的例子,对你来说可能更完整,处理大于128字节的字符串:http://coding.westreicher.org/?p = 23
如果您需要更多关于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();
Run Code Online (Sandbox Code Playgroud)
这将为您提供一个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());
Run Code Online (Sandbox Code Playgroud)
初始化密码后,我们已准备好加密数据.因为在加密之后,如果你看到它们"裸露",结果数据将没有多大意义,我们必须将它们封装在另一个对象中.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);
Run Code Online (Sandbox Code Playgroud)
生成的对象可以毫无顾虑地通过网络发送,因为它是加密的.唯一可以解密和获取数据的人是持有私钥的人.通常,这应该是服务器.为了解密消息,我们需要重新初始化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());
Run Code Online (Sandbox Code Playgroud)
既然密码已准备好解密,我们必须告诉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);
Run Code Online (Sandbox Code Playgroud)
在使用getObject方法时要小心,因为它返回一个Object的实例(即使它实际上是String的一个实例),而不是加密前它的Class实例,所以你必须将它转换为它事先形式.
以上内容来自:http://andreas.louca.org/2008/03/20/java-rsa-encryption-an-example/
RSA不适用于批量数据加密.相反,使用对称密码(如AES)来加密"大字符串".然后,使用RSA密钥加密用于AES的对称密钥.
BouncyCastle支持两种协议:S/MIME和PGP.所有敏感的隐私协议都以这种方式使用非对称算法进行密钥传输或密钥交换.
可以使用RSA加密的消息大小取决于密钥的模数,减去安全填充消息所需的一些字节.