RSA Bad Padding Exception

838 Views Asked by At

I am trying to RSA encrypt data on Android and send it to server(spring). getting BadPaddingException :

Approach: server send public key in a string, which i convert to PublicKey Object and send data from App after encryption as a string. server has a private key string , which is converted to PublicKey object and then data is decrypted.

Any Help would be much appreciated.

generation of key :

    public static KeyPair generateKeyPairRSA()  {
    try {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024, random);
        KeyPair keyPair = keyGen.generateKeyPair();
        return keyPair;
    } catch (Exception e) {
        Log.d(TAG,e.getLocalizedMessage());
    }
    return null;
}


public byte[] RSAEncrypt(final String plain, PublicKey publicKey) throws Exception {
    Cipher cipher = Cipher.getInstance(ALGO_RSA);
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] encryptedBytes = cipher.doFinal(plain.getBytes());
    return encryptedBytes;
}

public static PublicKey loadPublicKey1(String stored) throws Exception{
    byte[] data = Base64.decode(stored.getBytes());
    X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
    KeyFactory fact = KeyFactory.getInstance(ALGO_RSA);
    return fact.generatePublic(spec);
}

Server Methods :

public byte[] decryptRSA(String inputData) throws Exception {
    byte[] inputBytes = Base64.decodeBase64(inputData);
    PrivateKey key = loadPrivateKey(getPrivateKey());
    Cipher cipher1 = Cipher.getInstance("RSA");
    cipher1.init(Cipher.DECRYPT_MODE, key);
    return cipher1.doFinal(inputBytes);
}

private PrivateKey loadPrivateKey(String key64) throws Exception {
    byte[] pkcs8EncodedBytes = Base64.decodeBase64(key64);
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePrivate(keySpec);
}
1

There are 1 best solutions below

0
On

Got it Working. So diffrent libs have differenet implementation of Cipher. so while calling

Cipher.getInstance("RSA/ECB/PKCS1Padding");

Explicitly mention encryption mode and padding.

Hope it helps somebody.