开发者

Java AES decryption - can't decrypt string [duplicate]

开发者 https://www.devze.com 2023-04-13 02:29 出处:网络
This question already has an answer here: Closed 11 years ago. Possible Duplicate: Java AES Encrypt Entire String
This question already has an answer here: Closed 11 years ago.

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


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号