dariush
dariush

Reputation: 226

Encrypt in java with public key and decrypt in C# with private key RSA

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;

Upvotes: 0

Views: 593

Answers (1)

Maarten Bodewes
Maarten Bodewes

Reputation: 94058

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.

Upvotes: 1

Related Questions