1

I have read about this error but can't seem to get anything working.

The function of AES decrypt is:

  public static byte[] decrypted_Data(byte[] crypt) throws Exception {

  String seed = "SuperSecretPassword";

  KeyGenerator keygen = KeyGenerator.getInstance("AES");

  SecureRandom secrand = SecureRandom.getInstance("SHA1PRNG");

  secrand.setSeed(seed.getBytes());

  keygen.init(128, secrand);

  SecretKey seckey = keygen.generateKey();

  byte[] rawKey = seckey.getEncoded();

 SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");

 Cipher cipher = Cipher.getInstance("AES");

 cipher.init(Cipher.DECRYPT_MODE, skeySpec);

 byte[] decrypted = cipher.doFinal(crypt);

  return decrypted;
}

The function of encrypt is just the same except for

cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

I am calling these functions as follows on Android:

BufferedInputStream bis = new BufferedInputStream(photoStream);

byte[] mybytearray = new byte[photoStream.available()];

mybytearray = encrypted_Data(mybytearray);

And on the server as follows:

   byte[] mybytearray = new byte[10000000];

   mybytearray_1 = decrypted_Data(mybytearray_1);

This is the first time i use these encryption functions, what am I doing wrong as I am receiving:

javax.crypto.BadPaddingException: Given final block not properly padded 
Adroidist
  • 544
  • 3
  • 11
  • 23
  • 1
    You're generating a new random key to decrypt some text. If it waoks, then you're incredibly lucky! You must you the same key for decrypting than the one used for encrypting. Your IO code also looks wrong. Please provide an SSCCE that demonstrates the problem. – JB Nizet May 12 '12 at 09:49
  • I am sorry I am new to these stuff and I was following this link: http://securitymusings.com/article/2039/encrypt-stored-data-in-android How can i fix the different key issue? – Adroidist May 12 '12 at 09:53
  • 1
    Generate a key as you're doing, store it somewhere (in an instance variable, for example), and use this key as an argument to your encrypt() and decrypt() methods. – JB Nizet May 12 '12 at 09:56
  • The reason for the bad padding exception is that by using a different key, the end of your last block is effectively random, and does not match the expected padding patters, which the library code will always check. – rossum May 12 '12 at 14:34
  • Tried to contact the author of the explicit random number generator, not saving the secret key to a field. Then there is the problem with using ECB (which is the default). Unfortunately I could not contact them, don't trust code from Gemini Security solutions would be my recommendation. – Maarten Bodewes May 13 '12 at 09:15
  • I don't think this has anything to do with random keys. Assuming `seed` is identical on client and server, the same key should be generated. – vhallac May 14 '12 at 15:38
  • Refer this question and answer http://stackoverflow.com/questions/8049872/given-final-block-not-properly-padded?rq=1 – Hasitha Jul 05 '14 at 08:47

0 Answers0