Почему я получаю «BadPaddingException» при расшифровке? - PullRequest
1 голос
/ 10 января 2012

Вот мои настройки шифрования:

public static String encryptionAlgorithm = "AES";
public static short encryptionBitCount = 256;
public static int encryptionMessageLength = 176;
public static String hashingAlgorithm = "PBEWITHSHAAND128BITAES-CBC-BC";
       //PBEWithSHA256And256BitAES-CBC-BC"PBEWithMD5AndDES";//"PBKDF2WithHmacSHA1";
public static short hashingCount = 512;
public static String cipherTransformation = "AES/CBC/PKCS5Padding";

Вот мой код для расшифровки:

public byte[] readMessage () throws Exception
{
    byte[] iv = new byte[16];
    byte[] message = new byte[EncryptionSettings.encryptionMessageLength];

    try
    {
        // read IV from stream
        if (stream.read(iv) != 16)
            throw new Exception("Problem receiving full IV from stream");
    }
    catch (final IOException e)
    {
        throw new Exception("Unable to read IV from stream");
    }

    try
    {
        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
    }
    catch (final InvalidKeyException e)
    {
        throw new Exception("Invalid key");
    }
    catch (final InvalidAlgorithmParameterException e)
    {
        throw new Exception("Invalid algorithm parameter");
    }

    try
    {
        //read message from stream
        if (stream.read(message) != EncryptionSettings.encryptionMessageLength)
             throw new Exception("Problem receiving full encrypted message from stream");
    }
    catch (final IOException e)
    {
        throw new Exception("Unable to read message from stream");
    }

    try
    {
        return cipher.doFinal(message); //decipher message and return it.
    }
    catch (IllegalBlockSizeException e)
    {
        throw new Exception("Unable to decrypt message due to illegal block size - "
                          + e.getMessage());
    }
    catch (BadPaddingException e)
    {
        throw new Exception("Unable to decrypt message due to bad padding - "
                            + e.getMessage());
    }
}

Вот мой код для шифрования:

public void writeMessage (final byte[] message) throws Exception
{
    try
    {
        // write iv
        byte b[] = cipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV();
        System.out.println(b.length);
        stream.write(b);
    }
    catch (final InvalidParameterSpecException e) 
    {
        throw new Exception("Unable to write IV to stream due to invalid"+
                            " parameter specification");
    }
    catch (final IOException e)
    {
        throw new Exception("Unable to write IV to stream");
    }

    try
    {
        // write cipher text
        byte b[] = cipher.doFinal(message);
        System.out.println(b.length);
        stream.write(b);
    }
    catch (final IllegalBlockSizeException e)
    {
        throw new Exception("Unable to write cipher text to stream due to "+
                            "illegal block size");
    }
    catch (final BadPaddingException e)
    {
        throw new Exception("Unable to write cipher text to stream due to " +
                            "bad padding");
    }
    catch (final IOException e)
    {
        throw new Exception("Unable to write cipher text to stream");
    }
}

Ошибка: Unable to decrypt message due to bad padding - null.

При расшифровке я получаю исключение BadPaddingException, почему? Сообщение содержит ровно 168 символов, что составляет 176 после заполнения (делится на 16)

Ответы [ 2 ]

5 голосов
/ 13 января 2012

Из моего первоначального комментария:

Типичный сценарий - это сценарий, в котором ключ отличается от того, который используется на другой стороне.Это наиболее вероятная причина, но вы также можете проверить, как вы обрабатываете потоки, потому что вам действительно не хватает операторов .close () и, возможно, .flush ().Вы также предполагаете, что всегда можете прочитать все данные в буфер, что может быть не так.

Ключ действительно был рассчитан неправильно.

1 голос
/ 24 марта 2014

BadPaddingException Ошибка при шифровании / дешифровании

Я столкнулся с такой ошибкой, но это помогло мне

http://themasterofmagik.wordpress.com/2014/03/19/simple-aes-encryption-and-decryption-in-java-part1/

надеюсь, это вам тоже поможет.

...