简体   繁体   中英

Java - Decryption : javax.crypto.BadPaddingException

I get this warning:

javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.

Any ideas what causes this? Here are my encryption and decryption code. I have looked at a variety of different answers on StackOverflow but I was unable to find one that actually works.

    private static Cipher ecipher;
private static Cipher dcipher;

private static SecretKey key;

public static void Menu() {
    try {

        // generate secret key using DES algorithm
        key = KeyGenerator.getInstance("DES").generateKey();

        ecipher = Cipher.getInstance("DES");
        dcipher = Cipher.getInstance("DES");

        // initialize the ciphers with the given key
        ecipher.init(Cipher.ENCRYPT_MODE, key);

        dcipher.init(Cipher.DECRYPT_MODE, key);

    } catch (NoSuchAlgorithmException e) {
        System.out.println("No Such Algorithm:" + e.getMessage());
        return;
    } catch (NoSuchPaddingException e) {
        System.out.println("No Such Padding:" + e.getMessage());
        return;
    } catch (InvalidKeyException e) {
        System.out.println("Invalid Key:" + e.getMessage());
        return;
    }
}

public static String encrypt(String WordToEncrypt) {

    Menu();
    try {

        // encode the string into a sequence of bytes using the named charset
        // storing the result into a new byte array. 
        byte[] utf8 = WordToEncrypt.getBytes("UTF8");

        byte[] enc = ecipher.doFinal(utf8);

        // encode to base64
        enc = BASE64EncoderStream.encode(enc);
        System.out.println(new String(enc));

        return new String(enc);

    } catch (Exception e) {

        e.printStackTrace();

    }
    return null;
}

public static String decrypt(String WordToDecrypt) {
    Menu();
    try {
        // decode with base64 to get bytes
        byte[] dec = BASE64DecoderStream.decode(WordToDecrypt.getBytes());
        byte[] utf8 = dcipher.doFinal(dec);
        return new String(utf8, "UTF8");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;

}

}

You call Menu once in the encryption code and once in the decryption code. Since you generate the key randomly for both encryption and decryption, the key will differ and your code will fail.

Don't keep Cipher instances around, preferably not even in fields, but certainly not in class fields. DES is old; too old. Use AES - using DES isn't any easier than AES.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM