1

AES CBC обрезает строку, которая больше 16 символов. При следующем запуске выводит javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.

UPD: Вот проблемный код:

public static byte[][] encrypt(String txt, String txt2, String txt3){
try {
            SecretKey mysecretKey = new SecretKeySpec("qwertyuiopasdfgh".getBytes(), "AES");
            byte[] plainText1 = txt.getBytes();
            byte[] plainText2 = txt2.getBytes();
            byte[] plainText3 = txt3.getBytes();
            byte[][] plain_bytes = new byte[][] { plainText1, plainText2, plainText3 };
            IvParameterSpec iv = new IvParameterSpec("4283810222669651".getBytes());
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, mysecretKey, iv);
            cipher.update(plainText1);
            byte[] cipherText1 = cipher.doFinal();
            cipher.update(plainText2);
            byte[] cipherText2 = cipher.doFinal();
            cipher.update(plainText3);
            byte[] cipherText3 = cipher.doFinal();
            byte[][] encrypted_bytes = new byte[][] { cipherText1, cipherText2, cipherText3 };
            String str = Base64.getEncoder().encodeToString(encrypted_bytes[0]);
            encryptedUrl = str;
            System.out.println(encryptedUrl);
            return encrypted_bytes;
        } catch (Exception e1) {
            e1.printStackTrace();
            return null;
    
}
    }
1
  • Без исходников здесь не разобраться. Приложите свои исходники
    – Barmaley
    17 авг 2020 в 14:26

2 ответа 2

1

Нет, @Эникейщик, здесь все хитрее.

ТС пытается использовать мультипартное кодирование через cipher.update()/doFinal() и делает это неправильно.

Надо просто к каждому своему куску применять doFinal() примерно так:

cipher.init(Cipher.ENCRYPT_MODE, mysecretKey, iv);
cipherText1=cipher.doFinal(plainText1);
0

AES шифрует блоками по 128 бит (т.е. эти ваши 16 байт). Ошибка говорит вам, что последний блок меньше этого размера и его нужно чем-то заполнить, чтобы достичь 128 бит.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.