RSA encryption in Android and Java

后端 未结 3 1306
遇见更好的自我
遇见更好的自我 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:43

    There are deviations of different cipher and hash implementations. I would suggest using OpenSSL as a common implementation.

    0 讨论(0)
  • 2021-02-03 16:47

    I can´t comment yet so I answer.

    It is possible that different default configurations are being used. Check this question: Is there any difference between Apache's Base64.encodeBase64 and Android's Base64.encode with Base64.Default flag?

    0 讨论(0)
  • 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).

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