ArrayIndexOutOfBoundsException:RSA块的数据太多

时间:2013-07-23 13:04:02

标签: java android rsa

我的Android应用程序有些问题。我正在尝试与RSA加密/解密相关的应用程序。这是我的问题:

我可以清楚地加密短句,但是当我尝试将此消息解密为原始文本时,我会给出错误(“RSA块数据过多”)。而且,如果我想加密一个长句子我有相同的错误。我有一些搜索这个问题,并在这个网站找到了一些解决方案:

Site 1

Site 2

Site 3

但是我什么都不懂,这些解决方案非常复杂。我如何解决这个问题,谁能给我一个更简单的解决方案呢?谢谢。

编辑: 这些是我用于此项目的代码块。

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);
}

2 个答案:

答案 0 :(得分:20)

RSA只能加密比密钥对的模数短几个字节的消息。额外的字节用于填充,确切的数字取决于您使用的填充方案。

RSA用于密钥传输,而不是数据加密。如果您有长消息,请使用随机密钥使用AES对其进行加密。然后使用RSA使用消息接收者的公钥加密AES密钥。您应该使用Cipher班级的wrap()unwrap()方法。

这就是PGP,S / MIME,TLS(粗略)以及任何其他正确设计的RSA加密方案的工作原理。

答案 1 :(得分:0)

在我的用例中,我需要从我的应用程序加密一些请求数据到服务器。

如果我使用RSA加密AES密钥,这是没有意义的,因为使用RSA而不是AES,是为了防止逆向工程获取AES密钥(相对于RSA需要存储在服务器中的私钥进行解密) 。由于AES密钥需要在本地存储在应用程序中,因此我无法使用erickson建议的方法。

相反,我将长字符串拆分为List<String>(服务器提供商建议的每个长度);并加密每个字符串。

之后,List<String>将在json数组中传递给服务器,让服务器解密每个并重新加入它们。

当然,这种方法需要您的服务器支持,并且可能存在性能问题。