0

当我尝试将 a 转换hex string为 a 时,byte array我得到了这个异常:

Aug 15, 2013 10:17:32 PM Tester main
SEVERE: null
javax.crypto.BadPaddingException: Given final block not properly padded
        at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:811)
        at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
        at com.sun.crypto.provider.BlowfishCipher.engineDoFinal(BlowfishCipher.java:319)
        at javax.crypto.Cipher.doFinal(Cipher.java:1978)
        at Tester.main(Tester.java:21)

以下是尝试这样做的代码:

try {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
        SecretKey secretKey = keyGenerator.generateKey();
        Cipher cipher = Cipher.getInstance("Blowfish"); 
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        String decryptSt = new String(cipher.doFinal(DatatypeConverter.parseHexBinary("f250d7a040859d66541e2ab4a83eb2225d4fff880f7d2506")));
        System.out.println(decryptSt);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(Tester.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchPaddingException ex) {
        Logger.getLogger(Tester.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(Tester.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalBlockSizeException ex) {
        Logger.getLogger(Tester.class.getName()).log(Level.SEVERE, null, ex);
    } catch (BadPaddingException ex) {
        Logger.getLogger(Tester.class.getName()).log(Level.SEVERE, null, ex);
    }

问题是什么 ?为什么我得到一个例外?

4

1 回答 1

1

您永远无法使用随机密钥解密。如果这样做,您将获得由随机字节组成的明文。然而,密码试图取消填充消息。由于它没有找到有效的填充,你会得到这个异常。请注意 - 通过“运气”,大约 256 次 - 填充可能是正确的,在这种情况下,您只需将随机字节检索为纯文本。

于 2013-08-15T17:04:07.720 回答