0

the current decryption algorithm I wrote goes as follows,

    public String decrypt(String enc) throws Exception
    {
        Key key = k;
        Cipher crypt = Cipher.getInstance("AES");
        crypt.init(Cipher.DECRYPT_MODE,key);
        byte[] decrypt = crypt.doFinal(enc.getBytes());
        return new String(decrypt);
    }

The error that I get is at the line

 byte[] decrypt = crypt.doFinal(enc.getBytes());

I have seen similar questions as this posted, but I am using a 128 bit key, so I am pretty certain there is no padding.

This is how I generate the key

  public static SecretKey getKey() throws Exception
  {
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128); 
    return keyGen.generateKey();
  }

Additionally, decoding using base64 gives the same exact error

    public String decrypt(String enc) throws Exception
    {
        Key key = k;
        Cipher crypt = Cipher.getInstance("AES");
        crypt.init(Cipher.DECRYPT_MODE,key);
        byte[] decrypt = crypt.doFinal(Base64.getMimeDecoder().decode(enc));
        return new String(decrypt);
    }
OntologicalSin
  • 144
  • 2
  • 4
  • 15
  • General advice: **Always use a fully qualified Cipher string.** `Cipher.getInstance("AES");` may result in different ciphers depending on the default security provider. It most likely results in `"AES/ECB/PKCS5Padding"`, but it doesn't have to be. If it changes, you'll lose compatibility between different JVMs. For reference: [Java default Crypto/AES behavior](http://stackoverflow.com/q/6258047/1816580) – Artjom B. Mar 13 '17 at 06:18
  • **Never use [ECB mode](http://crypto.stackexchange.com/q/14487/13022)**. It's deterministic and therefore not semantically secure. You should at the very least use a randomized mode like [CBC](http://crypto.stackexchange.com/q/22260/13022) or [CTR](http://crypto.stackexchange.com/a/2378/13022). It is better to authenticate your ciphertexts so that attacks like a [padding oracle attack](http://crypto.stackexchange.com/q/18185/13022) are not possible. This can be done with authenticated modes like GCM or EAX, or with an [encrypt-then-MAC](http://crypto.stackexchange.com/q/202/13022) scheme. – Artjom B. Mar 13 '17 at 06:18

1 Answers1

1
public String decrypt(String enc)

The problem has already happened by the time you get here. The problem is that you are passing around ciphertext in a String. String isn't a container for binary data. Use a byte[].

user207421
  • 305,947
  • 44
  • 307
  • 483