0

This code is part of AES algorithm, does encryption and decryption, I have this method that return the encrypted value as [Hex], when I feed the encrypted value to be the input for decrypt method, I got this error: [Input length must be multiple of 16 when decrypting with padded cipher], any suggestion to fix it, please?

public static String encrypt(String Data) throws Exception {
    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.ENCRYPT_MODE, key);
    byte[] encVal = c.doFinal(Data.getBytes());
    // simply store the encoded byte array here
    byte[] bytes = Base64.getEncoder().encode(encVal);

    // loop over the bytes and append each byte as hex string
    StringBuilder sb = new StringBuilder(bytes.length * 2);
    for(byte b : bytes)
       sb.append(String.format("%02x", b));
    return sb.toString();
    }

public static String decrypt(String encryptedData) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGO);
        c.init(Cipher.DECRYPT_MODE, key);
        byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
        byte[] decValue = c.doFinal(decordedValue);
        String decryptedValue = new String(decValue);
        return decryptedValue;
    }
sara
  • 9
  • 2
  • As a block-cipher, `AES-128` encrypts multiples of `16 bytes`. To solve this you will need to implement some padding (there are different ways to do this). Take a look at [this](https://stackoverflow.com/questions/17773450/why-must-all-inputs-to-aes-be-multiples-of-16) – SuperKogito Apr 18 '19 at 14:55
  • Since the data were hex-encoded at the end of the `encrypt`-method, they must be hex-decoded at the beginning of the `decrypt`-method (for hex-decoding see e.g. https://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java). – Topaco Apr 18 '19 at 17:01

0 Answers0