我的 android 应用程序有一些问题。我正在尝试与 RSA 加密/解密相关的应用程序。这是我的问题:
我可以清楚地加密短句,但是当我尝试将此消息解密为原始文本时,我给出了一个错误(“RSA block 的数据太多”)。而且,如果我想加密一个长句子,我也会遇到同样的错误。我搜索了这个问题,并在这个网站上找到了一些解决方案:
但是我什么都不懂,这些解决方案太复杂了。我该如何解决这个问题,谁能给我一个更简单的解决方案?谢谢。
编辑: 这些是我用于该项目的代码块。
public String RSAEncrypt(String plain) throws NoSuchAlgorithmException, NoSuchPaddingException,InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException, UnsupportedEncodingException {
publicKey = getPublicKey();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherData = cipher.doFinal(plain.getBytes());
return Base64.encodeToString(cipherData, Base64.DEFAULT);
}
public String RSADecrypt(byte[] encryptedBytes) throws NoSuchAlgorithmException, NoSuchPaddingException,InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException, UnsupportedEncodingException {
privateKey = getPrivateKey();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] cipherData = cipher.doFinal(encryptedBytes);
return Base64.encodeToString(cipherData, Base64.DEFAULT);
}
最佳答案
RSA 只能加密比 key 对的模数短几个字节的消息。额外的字节用于填充,具体数量取决于您使用的填充方案。
RSA 用于 key 传输,而不是数据加密。如果您有一条长消息,请使用随 secret 钥使用 AES 对其进行加密。然后使用消息接收者的公钥用 RSA 加密 AES key 。您应该使用 Cipher 类的 wrap() 和 unwrap() 方法。
这就是 PGP、S/MIME、TLS(大致)和任何其他正确设计的 RSA 加密方案的工作原理。
关于java - ArrayIndexOutOfBoundsException : too much data for RSA block,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17811009/