0

im trying to encrypt and decrypt some data, when i go to run decrypt i get the error Input length must be multiple of 16 when decrypting with padded cipher.

Here is my Java class;

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import com.thoughtworks.xstream.core.util.Base64Encoder;

public class passwordEncoder {

        private static final String ALGORITHM       = "AES";
        private static final String myEncryptionKey = "ThisIsFoundation";
        private static final String UNICODE_FORMAT  = "UTF8";

        public static String encrypt(String valueToEnc) throws Exception {
            Key key = generateKey();
            Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.ENCRYPT_MODE, key);
            byte[] encValue = c.doFinal(valueToEnc.getBytes(UNICODE_FORMAT));
            //String encryptedValue = new Base64Encoder().encode(encValue);
            String encryptedValue = new Base64Encoder().encode(encValue);
            return encryptedValue;
        }

        public static String decrypt(String encryptedValue) throws Exception {
            Key key = generateKey();
            Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.DECRYPT_MODE, key);
            byte[] decordedValue = new Base64Encoder().decode(encryptedValue);
            byte[] decValue = c.doFinal(decordedValue);
            String decryptedValue = new String(decValue);
            return decryptedValue;
        }

        private static Key generateKey() throws Exception {
            byte[] keyAsBytes;
            keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
            Key key = new SecretKeySpec(keyAsBytes, ALGORITHM);
            return key;
        }
}

Any suggestions/help on how i would fix this error would be appreciated.

Strelok
  • 50,229
  • 9
  • 102
  • 115
  • 1
    It's a bad idea to use default provider values for crypto padding/mode. Use an algorithm specifier like ""AES/CBC/PKCS5Padding", instead. – BadZen Apr 20 '19 at 14:21
  • Possible duplicate of [javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher in tcp](https://stackoverflow.com/questions/39498722/javax-crypto-illegalblocksizeexception-input-length-must-be-multiple-of-16-when) (although the "correct" answer is not marked as such there!) – BadZen Apr 20 '19 at 14:22
  • Make sure the generated ciphertext is identical as output of the encrypt and as input of the decrypt. Encrypt in ECB or CBC mode always generates N blocks of output for any plaintext. You're currently trying to decrypt a partial block of data using the block cipher, which fails. – Maarten Bodewes Apr 20 '19 at 21:21

0 Answers0