0
votes

I use Android deivces to encript a string with these code:

Android side , key length : 2048

//Init: need time
private void prepareEncrypt(String publicKey) throws Exception {
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey.getBytes()));
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey pubKey = keyFactory.generatePublic(keySpec);
    cp = Cipher.getInstance("RSA/ECB/OAEPWithSHA-512AndMGF1Padding");
    cp.init(Cipher.ENCRYPT_MODE, pubKey);
}

//encrypt
private byte[] encryptByPublicKey(byte[] data) {
    //data = Base64.getEncoder().encode(data);
    byte[] result = new byte[0];
    try {
        result = cp.doFinal(data);
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    }

    return result;
}

Get a Ciphertext A.

Then i tried to decode the A with Java on elipse:

public static byte[] decryptByPrivateKey(byte[] encrypted, byte[] privateKey) throws Exception {
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey keyPrivate = kf.generatePrivate(keySpec);
    Cipher cp = Cipher.getInstance("RSA/ECB/OAEPWithSHA-512AndMGF1Padding");
    cp.init(Cipher.DECRYPT_MODE, keyPrivate);
    byte[] arr = cp.doFinal(Base64.getDecoder().decode(encrypted));
    return arr;
}

I always failed to decode the String.

javax.crypto.BadPaddingException: Decryption error
    at sun.security.rsa.RSAPadding.unpadOAEP(Unknown Source)
    at sun.security.rsa.RSAPadding.unpad(Unknown Source)
    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:363)
    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)

If the Android do not change the TRANSFORMATION paremeter on object Cipher Like:

RSA/ECB/NoPadding

RSA/ECB/PKCS1Padding

RSA/ECB/OAEPWithSHA-1AndMGF1Padding

RSA/ECB/OAEPWithSHA-224AndMGF1Padding

RSA/ECB/OAEPWithSHA-256AndMGF1Padding

RSA/ECB/OAEPWithSHA-384AndMGF1Padding

RSA/ECB/OAEPWithSHA-512AndMGF1Padding

How to decode the Ciphertext A successfully?

1

1 Answers

0
votes

Need this :

    OAEPParameterSpec oaepParameterSpecDec = new OAEPParameterSpec("SHA-512", "MGF1", new MGF1ParameterSpec("SHA-512"), PSource.PSpecified.DEFAULT);
    ...
    cp.init(Cipher.DECRYPT_MODE, keyPrivate, oaepParameterSpecDec);

obviously give the padding paremeters