RSA encryption in Android and Java

后端 未结 3 1305
遇见更好的自我
遇见更好的自我 2021-02-03 16:32

I would like to encrypt a String with RSA encryption. My public/private keys were generated and stored in DB. In android, I use this code:

public static String e         


        
3条回答
  •  生来不讨喜
    2021-02-03 16:48

    It looks like you've been undone by relying on defaults. Never do that if you hope for interoperability.

    Here are the two examples of mistakenly relying on defaults in your code that I've found.

    final Cipher cipher = Cipher.getInstance("RSA");

    The tranformation string is supposed to be of the form "algorithm/mode/padding" but you've left off the mode and padding specifications. As a result you got default values for those. The defaults are evidently different on Android and Oracle Java. You should always fully specify the transformation, for example:
    final Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");

    Another bad example is cipherText = cipher.doFinal(text.getBytes());

    In text.getBytes() you are relying on the no-args getBytes() method which uses the default charset for the platform. But this default charset differs on different platforms, and thus this is not portable. In almost all cases I've run across you should specify the UTF-8 charset. So the correct line would thus be
    cipherText = cipher.doFinal(text.getBytes("UTF-8"));

    and the correct string constructor to use to recreate the original string in the decrypt method is the String(byte [] data, String charsetName).

提交回复
热议问题