Java RSA加密

我试图来回编码一个简单的字符串“测试”。

public static String encode(Key publicKey, String data) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { byte[] byteData = data.getBytes(); // convert string to byte array Cipher cipher = Cipher.getInstance(ALGORITHM); // create conversion processing object cipher.init(Cipher.ENCRYPT_MODE, publicKey); // initialize object's mode and key byte[] encryptedByteData = cipher.doFinal(byteData); // use object for encryption return new String(encryptedByteData); // convert encrypted byte array to string and return it } public static String decode(Key privateKey, String data) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { byte[] byteData = data.getBytes(); // convert string to byte array Cipher cipher = Cipher.getInstance(ALGORITHM); // create conversion processing object cipher.init(Cipher.DECRYPT_MODE, privateKey); // initialize object's mode and key System.out.println(byteData.length); byte[] decryptedByteData = cipher.doFinal(byteData); // use object for decryption return new String(decryptedByteData); // convert decrypted byte array to string and return it } 

但是,尽管加密工作正常(ALGORITHM是“RSA”),但在尝试解密我刚从加密“test”获得的字符串时,我得到以下exception:

javax.crypto.IllegalBlockSizeException:数据不得超过256个字节

我应该将加密的字节分成256块,以便能够解密吗?

您无法将随机字节可靠地转换为String 。 结果取决于运行此命令的计算机上的默认字符编码。 使用多种编码时,密文将被破坏,信息将丢失。

修改代码以使用byte[] (’doFinal()`方法的结果。

如果需要将byte[]转换为字符串,请使用Base-64之类的编码。

从这里 :

RSA算法只能加密具有最大字节长度RSA密钥长度的数据,以8位减去11个填充字节的比特,即最大字节数=密钥长度(位/ 8-11)。如果要加密更大的数据,然后使用更大的密钥,例如,具有4096位的密钥将允许您加密501字节的数据。

如果您有一个长数据,您应该将其拆分为适合和加密/解密每个数据的数据块(不是一个好主意)或使用对称算法(AES / DES / RC4 /等)加密/解密它们,使用RSA公钥加密对称密钥,并将两者发送到另一端。 (更好的主意)。

第二种方法是一种非常常见的方法,因为非对称加密算法比对称算法(加密和解密)都要昂贵得多。