Question

I am trying to encrypt a string in ruby and descrypt in Android. I'm pretty unfamiliar with ciphering, but I've done some reading and I think I'm close to getting to work. however, I'm still getting an error on the Android side that I just do not understand how to fix. I understand what padding is and that it's not correct, but what do I need to change to make this work? My ruby and java code are below. Thank you!!!

Ruby:

shared_key = "123456789012345678901234"      
cipher = OpenSSL::Cipher::Cipher.new("des3")
cipher.encrypt
cipher.key = shared_key
ciphertext = cipher.update(secret)
ciphertext << cipher.final
Rails.logger.debug(ciphertext);

encrypted_secret = Base64.encode64(ciphertext)
Rails.logger.debug(encrypted_secret);
render json: { 'token' => token, 'secret' => encrypted_secret }, status: :ok

Java:

    SecretKey key = new SecretKeySpec(SHARED_DECRYPTION_KEY.getBytes("UTF8"), "DESede");
    byte[] encryptedSecretBytes = Base64.decode(secret);     
    Cipher cipher = Cipher.getInstance("DESede"); // cipher is not thread safe
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] plainTextSecretBytes = (cipher.doFinal(encryptedSecretBytes));
    String decryptedSecret = Base64.encodeBytes(plainTextSecretBytes);

and the exception I get in Android:

05-14 19:03:11.500: W/System.err(22175): javax.crypto.BadPaddingException: pad block corrupted
05-14 19:03:11.500: W/System.err(22175):    at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(BaseBlockCipher.java:709)
05-14 19:03:11.500: W/System.err(22175):    at javax.crypto.Cipher.doFinal(Cipher.java:1111)
05-14 19:03:11.500: W/System.err(22175):    at com.cdlcollege.saas.Credentials.storeServerAccessCredentials(Credentials.java:85)
Was it helpful?

Solution

Pad block corrupted means the wrong key was used to decrypt or the data was altered between encryption and decryption.

If I had to guess, I suspect you are creating a key in the wrong manner. Instead of calling getBytes(), I'm guessing you should have done a hex conversion.

See Convert hex string to byte [] for example Android code for performing this task.


Side note: don't just specify "DESede" for a cipher. Specify the mode and padding as well. E.g. "DESede/CBC/PKCS5Padding". That ensures you get exactly what you want, rather than crypto provider defaults (which may vary across phones).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top