使用RSA加密和解密Java中的大字符串

我正在尝试实施PKI。我想在Java中使用RSA而不使用弹性城堡来加密大字符串。我得到的问题是数据不得超过117个字节。我尝试寻找失败的解决方案。我是这种加密的新手。请提供一个大字符串作为示例来帮助我并进行解释。

回答:

一次不能使用超过128个字节的RSA加密解密。您必须拆分数据并在循环中进行处理,几乎可以随时将字节写入String /

Array。如果您唯一的问题是数据大小,那么您可能没有更多的选择了。只是拆分数据。

一般而言,如果您需要有关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());

初始化密码后,我们就可以加密数据了。由于在加密之后,如果您看到的是“裸露”的结果数据就没有多大意义,因此我们必须将它们封装在另一个Object中。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());

现在密码已准备好解密,我们必须告诉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的实例,所以您必须将其强制转换为它的事先表格。

以上内容来自:http : //andreas.louca.org/2008/03/20/java-rsa-encryption-an-

example/

以上是 使用RSA加密和解密Java中的大字符串 的全部内容, 来源链接: utcz.com/qa/422451.html

回到顶部