AES encryption / decryption from Android to server

I have one server and two clients. The server works with Java and Jersey (Rest). One client is a Java client and the other is an Android client.

I want to send a message encrypted with AES. So I have this code (on server and clients):

cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

public String crypterMessage(String message) {
        cipher.init(Cipher.ENCRYPT_MODE, key);
        String messageCrypte = new String(Hex.encodeHex(cipher.doFinal(message.getBytes())));
        mIv = cipher.getIV();
        return messageCrypte;
}

public String decrypterMessage(String messageCrypte) {
        IvParameterSpec ivParameterSpec = new IvParameterSpec(mIv);
        cipher.init(Cipher.DECRYPT_MODE, obtenirCleSecrete(), ivParameterSpec);
        return new String(cipher.doFinal(Hex.decodeHex(messageCrypte.toCharArray())));
}

      

When I send an encrypted message from a Java client, the server decrypts it and encrypts the response. The Java client decrypts the response. It works great.

But when the Android client sends an encrypted message, the server cannot decrypt it. I have a BadPaddingException: "Considering the last block is not padded correctly" on the server.

The java server and client are using SunJCE and the Android client is using AndroidOpenSSL as the provider.

What's the problem with Android?

PS: I am using Hex.encode and Hex.decode from org.apache.commons. And I am using Spring on Android.

EDIT

I found the problem, but I don't know why. I have this code:

KeyGenerator generateurCle = KeyGenerator.getInstance("AES");
        SecureRandom securite = SecureRandom.getInstance("SHA1PRNG");
        securite.setSeed(mCleCryptage.toByteArray());
        generateurCle.init(128, securite);
        mCleSecrete = generateurCle.generateKey();

      

The "mCleCryptage" variable is the same for server and clients. But "mCleSecrete" is different between Android server and client. Java server and client share the same secret key.

I don't understand because everyone has the same class, the same code.

+3


source to share


1 answer


I found a solution. The problem was securite.setSeed (). You can see the solution here in the first post



+1


source







All Articles