I encrypt a string in Android by the public key. However, I get an exception "Decryption error" when I try to decrypt the encrypted string by the private key in pure Java code. Can anyone help to find the problem?
Android code to encrypt
import android.util.Base64;
public static String encryptMessage(final String plainText, final PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithAndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return Base64.encodeToString(cipher.doFinal(plainText.getBytes()), Base64.NO_WRAP);
}
Pure Java code to decrypt
import java.util.Base64;
public static String decryptMessage(final String encryptedText, final PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithAndMGF1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
Base64.Decoder decoder = Base64.getDecoder();
byte[] byteArray = decoder.decode(encryptedText);
byte[] decryptedArray = cipher.doFinal(byteArray); // throw exception here
String plainText = new String(decryptedArray);
return plainText;
}
You may notice I have to use different Base64 APIs in Android and pure Java. I tried "RSA/ECB/PKCS1Padding", and it can decrypt correctly without the exception. Tried "RSA/ECB/OAEPWithSHA-256AndMGF1Padding" too but got the same exception.
OAEPWithMD5AndMGF1Padding
. Here it must be taken into account that OAEP uses digests in two places: as the basis for the mask generation function MGF1 and for the hashing of the OAEP label (for details see RFC 8017). For decryption both digests must be identical to those for encryption. To test this, both digests can be explicitly defined withOAEPParameterSpec
. – TopacoOAEPWithMD5AndMGF1Padding
, which applies MD5 for label and MGF. For Java 8,OAEPWithMD5AndMGF1Padding
the SunJCE provider is used by default, which applies MD5 for the label but SHA1 for the MGF. Since the digests differ, the ciphertext generated with Android can't be decrypted with Java ifOAEPWithMD5AndMGF1Padding
is used in both codes. This problem can be eliminated withOAEPParameterSpec
. It might be worthwhile to check the providers and, if necessary, adjust the digests withOAEPParameterSpec
. – Topaco