Java RSA Encryption

后端 未结 3 1748
灰色年华
灰色年华 2021-02-04 13:42

I am trying to encode a simple String \"test\" back and forth.

public static String encode(Key publicKey, String data) throws NoSuchAlgorithmException, NoSuchPad         


        
相关标签:
3条回答
  • 2021-02-04 14:22

    From here:

    The RSA algorithm can only encrypt data that has a maximum byte length of the RSA key length in bits divided with eight minus eleven padding bytes, i.e. number of maximum bytes = key length in bits / 8 - 11. If you want to encrypt larger data, then use a larger key, for example, a key with 4096 bits will allow you to encrypt 501 bytes of data.

    0 讨论(0)
  • 2021-02-04 14:24

    You can't reliably convert random bytes to a String. The results will depend on what your default character encoding is on the machine where you run this. With many encodings, the cipher text will be corrupted, and information will be lost.

    Modify your code to use a byte[] instead (the result of the 'doFinal()` method.

    If you need to convert the byte[] to a character string, use an encoding like Base-64.

    0 讨论(0)
  • 2021-02-04 14:26

    If you have a long data, you should either split it to data chunks that fits and encrypt / decrypt each of them (not such a good idea) or encrypt / decrypt them using a symmetric algorithm (AES / DES / RC4 / etc.), encrypt the symmetric key with the RSA public key and send both to the other side. (much better idea).

    The second approach is a very common approach, since asymmetric encryption algorithms are much more expensive than symmetric algorithms (for both encryption and decryption).

    0 讨论(0)
提交回复
热议问题