java.lang.ArrayIndexOutOfBoundsException: too much data for RSA block

后端 未结 3 427
野趣味
野趣味 2021-01-03 13:46

I\'m using RSA encrypt text and decrypt text. The public key and the private key are generated with openssl tool. I encountered an \"java.lang.ArrayIndexOutOfBoundsException

3条回答
  •  攒了一身酷
    2021-01-03 14:05

    You are missing some steps in your code which makes it impossible to check. However, there are a few clues to suggest a problem. Your decryptData method takes a String argument and then calls String.getBytes() to get the data which is then decrypted. However, the result of encryption is a sequence of bytes which is not the encoding of any valid String. Perhaps you meant to base64 decode the input instead of calling getBytes(). In general to perform decryption and decoding you must reverse the steps you performed during encryption and encoding. So, if the plaintext is a byte[] then the steps are:

    byte [] → Encrypt → byte [] → Base64 encode → String.

    then, in the decrypt direction you start with a Base64 string, you must, in order:

    String → Base64 decode → byte [] → decrypt → byte []

    Also, another issue which is bad practice and a source of many portability bugs is the use of defaults. You are using defaults in two places and they're both troublesome. First you are using the default no-args String.getBytes() method, and presumably matching that up with the one-arg String (byte []) constructor. This use the platform default character set, but this can differ on different platforms. Therefore always specify a character set. For most applications 'UTF-8' is an ideal choice. Secondly, you are calling Cipher.getInstance('RSA') without specifying padding. Oracle's Java and Android's Java will give you different padding and thus your code will not be portable between the platforms. Always specify the complete padding string. Here the choice is little more difficult if you need portability to older Java implementations. OAEP padding should be your first choice, so Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding"); is probably the right choice. See this for further discussion.

    As for how to encrypt longer texts, see the answer from Henry.

提交回复
热议问题