Java Android Error "too much data for RSA block"



我的Android项目中有一个错误(RSA加密/解密)。加密通过可以,但当我试图解密加密文本时,出现错误:"RSA块的数据太多"

如何解决这个问题?

代码:

public String Decrypt(String text) throws Exception
{
    try{
        Log.i("Crypto.java:Decrypt", text);
        RSAPrivateKey privateKey = (RSAPrivateKey)kp.getPrivate();
        Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] cipherData = cipher.doFinal(text.getBytes());// <----ERROR: too much data for RSA block
            byte[] decryptedBytes = cipher.doFinal(cipherData);
            String decrypted = new String(decryptedBytes);
            Log.i("Decrypted", decrypted);
        return decrypted;
    }catch(Exception e){
        System.out.println(e.getMessage());
    }
    return null;
}

您的问题是,如果您想使用文本表示(在您的情况下为String)传输密文,则需要对其进行编码/解码(代码中只有text)。

试着在这个网站上查找base64编码,应该有很多关于它的信息。加密后编码,解密前解码。您还应该为明文指定一个特定的字符编码。

最后,您可能应该使用对称密码进行加密,并使用RSA加密对称密钥。否则,RSA计算中的空间可能会用完,因为公钥无法加密大于其模数(密钥大小)的数据。

最新更新