0

I have an public key that was generated in C# in the back end.

I want to encrypt the message in Android / Java, but when I encrypt the message, the encrypted message is not same as in C#.

I tried encrypting with this specification for the RSA algorithm:

‫‪KeyExchangeAlgorithm‬‬ ==> ‫‪RSA-PKCS1-KeyEx‬‬
‫‪KeySize‬‬ ==>2048 
‫‪RSAEncryptionPadding‬‬ ==> ‫‪false‬‬

This is specification that the back end expects me; below is my implement algorithm on Android.

String encoded = "";

byte[] encrypted = null;
try {

    byte[] publicBytes = Base64.decode(PUBLIC_KEY,Base64.DEFAULT);
    byte[] exponent = Base64.decode("AQAB",Base64.DEFAULT);
    BigInteger key = new BigInteger(1,publicBytes);
    BigInteger expo = new BigInteger(1,exponent);
    RSAPublicKeySpec keySpec = new RSAPublicKeySpec(key,expo);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey pubKey = keyFactory.generatePublic(keySpec);

    Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");

    //Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);
    encrypted = cipher.doFinal(txt.getBytes());
    encoded = Base64.encodeToString(encrypted, Base64.DEFAULT);
}
catch (Exception e) {
    e.printStackTrace();
    Log.e("3771",""+e.getMessage());
}
return encoded;
5
  • The default padding in java and c# are different. You need to sue the same padding. See following : stackoverflow.com/questions/30849594/… Commented Jan 7, 2020 at 17:45
  • thanks, but in my case sha is not used, i want algorithm like this ‫‪KeyExchangeAlgorithm‬‬ ==> ‫‪RSA-PKCS1-KeyEx‬‬ ‫‪KeySize‬‬ ==>2048 ‫‪RSAEncryptionPadding‬‬ ==> ‫‪false‬‬ Commented Jan 7, 2020 at 17:51
  • You need to use the same public and private key when encrypting and decrypting. Commented Jan 7, 2020 at 18:01
  • key are same result is different, and i just use public key for encrypt Commented Jan 7, 2020 at 18:13
  • Formatting improvements. Commented Jan 7, 2020 at 21:54

1 Answer 1

1

RSA uses random padding, so the signature is supposed to be different every time. Use PKCS#1 v1.5 padding ("PKCS1Padding" for historical reasons) and the test is in verification, not in encrypting the same message again.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.