Fustigador
Fustigador

Reputation: 6459

Decrypt a String encoded using AES 256

Totally security noob here.

I have to decrypt a String I receive, encoded in Base64. All I have is the String I need to decrypt, and a String, which the service that sents me the String to decode calls it a seed.

Based on what I have read here and in other places, I have this:

public String decrypt(String message) throws Exception
{
    String salt = "PRUEBA";
    Cipher c = Cipher.getInstance("AES");
    SecretKeySpec key = new SecretKeySpec(salt.getBytes(), "AES");
    c.init(Cipher.DECRYPT_MODE, key);
    byte[] decordedValue = Base64.decode(message.getBytes(), Base64.DEFAULT);
    byte[] decValue = c.doFinal(decordedValue);
    String decryptedValue = new String(decValue);
    String decoded=new String(Base64.decode(decryptedValue,Base64.DEFAULT));
    return decoded;
}

This returns java.security.InvalidKeyException: Key length not 128/192/256 bits.

I tried also this library, but it returns IllegalBlockSizeException: last block incomplete in decryption

Don't know if I need something else from the server side, as I said I have little to no knowledge of encryption.

I am completely lost at this issue. Can you help me?

Thank you.

Upvotes: 0

Views: 1547

Answers (1)

gusto2
gusto2

Reputation: 12075

There are multiple issues with your code and you are missing some critical information (you may ask from the system sending data)

You are missing Cipher, IV (optionally) and key

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

Using only AES cipher with no IV parameter means you are using AES/ECB/PKCS5Padding cipher. Are you sure you suppose to use this cipher? Shouldn't it be AES/CBC/PKCS5Padding ? Ask the system doing the encryption what the encryption should be (including mode and padding). Knowing it's AES may not be sufficient.

If the mode used needs IV (initialization vector), you need to know its value. Usually IV is 128 bits (16 bytes) prepended to the ciphertext, but you need to know that for sure.

String salt = "PRUEBA";
SecretKeySpec key = new SecretKeySpec(salt.getBytes(), "AES");

And - you need a key (without the key you won't decrypt).

As already commented, the key needs to be 128, 192 or 256 bits long (=16, 24 or 32 bytes). If it is to be generated from another string, you need to know how.

String decryptedValue = new String(decValue);
String decoded=new String(Base64.decode(decryptedValue,Base64.DEFAULT));

Are you sure that the decrypted value is base64 encoding of another String?

Just to get some examples for Java crypto, you may have a loot at my blog too.

Upvotes: 1

Related Questions