0

Hello I was looking for answers in stack overflow. But any of this dont work. Could you please help me.

I'd like to do encryption and decryption text in android. Id like to do it as simple as I can. Firstly I wrote some code in java eclipse. It work fine but if i transfer it to Android Studio there is couple of errors.

I must transfer bytes[] to String because i use Firebase and this not support storing class object with bytes[]

I try to work with this hint, and many others but I have only failure.

generateKey()

private static SecretKey generateKey() throws Exception
    {

        SecretKey  key = new SecretKeySpec(org.apache.commons.codec.binary.Hex.decodeHex(klucz.toCharArray()), "AES");         

        return key;
    }

encrypt(msg)

public String encrypt(String messageText)
{
    try
    {
        byte[] data = messageText.getBytes("UTF-8");


        IvParameterSpec iv = new IvParameterSpec(iv_.getBytes("UTF-8"));
        SecretKeySpec key = (SecretKeySpec) generateKey();

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);


        byte[] textBytes = cipher.doFinal(messageText.getBytes("UTF-8"));
        String textString = Base64.encodeToString(textBytes, Base64.DEFAULT);

        return  textString;


    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }

    return null;
}

decrypt(msg)

   public String decrypt(String msgText)
    {
        try
        {
            byte[] data = msgText.getBytes("UTF-8");

            IvParameterSpec iv = new IvParameterSpec(iv_.getBytes("UTF-8"));
            SecretKeySpec skeySpec = (SecretKeySpec) generateKey();

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);


            byte[] original = cipher.doFinal(data);
            String textString = new String(original, "UTF-8");
            return textString;


        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

        return null;
    }

When I do sth like this I got error:

WRONG_FINAL_BLOCK_LENGTH

When I try to change it to simple AES with

Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);

I got error:

IllegalBlockSizeException:

Community
  • 1
  • 1
Kainka
  • 370
  • 2
  • 6
  • 20

1 Answers1

2

You have encoded the ciphertext in base64 after encryption, but you have not decoded it before decryption

Remove in decrypt() this code

  byte[] data = msgText.getBytes("UTF-8");

And add

byte[] data = Base64.decode(msgText, Base64.DEFAULT);

Note: do not use AES in Cipher cipher = Cipher.getInstance("AES");. Use a specific mode to avoid unexpected results in android

pedrofb
  • 37,271
  • 5
  • 94
  • 142