0

Possible Duplicate:
Java AES Encrypt Entire String

I've run into a small problem. For some reason, I can't decrypt some strings using the same method that I encrypt them. For example, I'm using this code for decrypting:

        SecretKeySpec key = new SecretKeySpec(salt.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
    cipher.init(Cipher.DECRYPT_MODE, key);
    String result = new String(cipher.doFinal(message));

    System.out.println("Decrypted:" + result);

Anyway, when the salt is "1231231231231231" and the message that im trying to decrypt is "read". I get this error:

Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded

But the encryptor (which works the same way) says the encrypted value is

I¡?Þd↨Ú#à, 7êLO* 

How can I fix this or avoid the user from inputting such strings? Thansk

6
  • 1
    "please ignore the messiness" No problem, I'll just ignore your post. Oct 16, 2011 at 5:44
  • 1
    That has to go down as the 'dummy spit of the week'. I recommend reading How To Ask Questions The Smart Way, with particular reference to On Not Reacting Like A Loser. Good luck! Oct 16, 2011 at 6:02
  • 1
    "...and the message to be encrypted is 'read'": aren't you trying to decrypt? You need to pass in the output of an encrypt operation with the same padding to the above function.
    – vhallac
    Oct 16, 2011 at 6:18
  • sorry, thats what i ment. After encrypting "read" the output is "I¡?Þd↨Ú#à, 7êLO*" but when I try to decrypt that with the same key I get the error I posted. I edited the initial post.
    – Cody
    Oct 16, 2011 at 6:21
  • 1
    And do you also encrypt with PKCS#5 padding? In any case, you can decrypt with no padding, and look at the decrypted data to see why JCE thinks the padding is not PKCS#5.
    – vhallac
    Oct 16, 2011 at 6:35

1 Answer 1

0

Solution: don't store it in a string.

Your call to Cipher.doFinal should be stored in a byte array (byte[]), and your input to the decryption should likewise be a byte array. If you're taking a String input, use .getBytes(); when you're creating the String for an output, use new String(myArray)

1
  • yah i know, this is how my program works: string gets encrypted (output is byte). output is converted to string and stored in a seperate text file. it's then read from the text file and converted back to byte. decryptor decrypts the byte. but apperantly byte[] result = cipher.doFinal(message.getBytes()); String stringResult = new String(result); stringResult.getBytes() does not reverse the process entirely
    – Cody
    Oct 16, 2011 at 7:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.