Home > OS >  javax.crypto.BadPaddingException: Given final block not properly padded. AES Decryption
javax.crypto.BadPaddingException: Given final block not properly padded. AES Decryption

Time:11-14

Implement UDP chat application using symmetric AES encryption. I start with the client side having a message and sending the message encrypted (ciphertext) to the server side. Then the server side will decrypt with the fixed key and the ciphertext to get the original message. Both the server-side and client-side will use this key for encrypting and decrypt

client.sentThenReceive(" P@ssword123@@24".getBytes(StandardCharsets.UTF_8));
server.receiveThenSend(" P@ssword123@@24".getBytes(StandardCharsets.UTF_8));

Everything worked properly until I try to decrypt method on the server side with the ciphertext and given the key causing the error below in this line of code

byte[] originalMessage = cipher.doFinal(message);
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
    at java.base/com.sun.crypto.provider.CipherCore.unpad(CipherCore.java:858)
    at java.base/com.sun.crypto.provider.CipherCore.fillOutputBuffer(CipherCore.java:938)
    at java.base/com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:734)
    at java.base/com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:434)
    at java.base/javax.crypto.Cipher.doFinal(Cipher.java:2206)
    at Server.Decryption(Server.java:45)
    at Server.receiveThenSend(Server.java:63)
    at Server.main(Server.java:81)

Here is the encryption method in the client side, after the client encrypte the message and send it to the client side

public byte[] Encryption(byte[] message, byte[] keyBytes)throws InvalidKeyException, NoSuchPaddingException,
        NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {
    // Step 5: Create a Cipher object
    Cipher cipher = Cipher.getInstance("AES");
    SecretKey secrekey = new SecretKeySpec(keyBytes, "AES");
    cipher.init(cipher.ENCRYPT_MODE, secrekey);
    byte[] Encryption = cipher.doFinal(message);
    return Encryption;
}

When the Server side receive the encrypted message from the client side, it will using decrypte method to decrypt. The error evoke by this line of code: byte[] originalMessage = cipher.doFinal(message);

public String Decryption(byte[] message, byte[] keyBytes)throws InvalidKeyException, NoSuchPaddingException,
        NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {

        Cipher cipher = Cipher.getInstance("AES");
        SecretKey secretKey = new SecretKeySpec(keyBytes, "AES");
        cipher.init(cipher.DECRYPT_MODE, secretKey);
        byte[] originalMessage = cipher.doFinal(message);
        return new String(originalMessage);
}

This is the send method in client side use to send the ciphertext to server side


public void sentThenReceive(byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    Scanner scanner = new Scanner(System.in);
    while (true) {
        try {
            String messageToSend = scanner.nextLine();
            byte[] message = messageToSend.getBytes();
            DatagramPacket datagramPacket = new DatagramPacket (message, message.length, inetAddress, 2468);
            datagramSocket.send(datagramPacket);

This is the receive method in the server side use to receive the message from client side

public void receiveThenSend(byte[] key) throws NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
    while (true) {
        try {
            DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
            datagramSocket.receive(datagramPacket);
            System.out.println(Decryption(datagramPacket.getData(),key));
            InetAddress inetAddress = datagramPacket.getAddress();
            int port = datagramPacket.getPort();
            datagramPacket = new DatagramPacket(buffer, buffer.length, inetAddress, port);
            datagramSocket.send(datagramPacket);

I'm a learner so anyone please feel free to teach me what wrong with my code and how I can fix it. I would very appreciate your input!

CodePudding user response:

There are two general causes of a Bad Padding exception, either different modes set or failed decryption.

First check that you have explicitly set the padding mode the same on both sides.

If not that, then you need to check that the whole decryption has not failed, resulting in garbage instead of well formed padding. Temporarily set the decryption side to "NoPadding" and see what the result is. Complete garbage means you have a more general decryption failure. A mostly good decryption, with some extra bytes at the end is a good decryption with added padding. You need to set the decryption side to expect that type of padding. Do not leave "NoPadding" set as it is less secure.

  • Related