簡體   English   中英

Java - 解密:javax.crypto.BadPaddingException

[英]Java - Decryption : javax.crypto.BadPaddingException

我收到此警告:

javax.crypto.BadPaddingException:給定的最終塊未正確填充。 如果在解密過程中使用了錯誤的密鑰,則可能會出現此類問題。

任何想法是什么原因造成的? 這是我的加密和解密代碼。 我在 StackOverflow 上查看了各種不同的答案,但找不到真正有效的答案。

    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;

}

}

您在加密代碼中調用Menu一次,在解密代碼中調用一次。 由於您為加密和解密隨機生成密鑰,因此密鑰會有所不同並且您的代碼將失敗。

不要保留Cipher實例,最好不要放在字段中,但絕對不要放在類字段中。 DES 是舊的; 舊了。 使用 AES - 使用 DES 並不比 AES 容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM