BadPaddingException:给定最终块未正确填充

And*_*zzi 5 java encryption

我有一个带有DES/ECB/PKCS5Padding的私钥文件(由一个秘密短语生成的56位DES密钥),我想解密它.我不知道为什么,但每次我尝试decript,我的密码类的方法doFinal抛出这个错误:

javax.crypto.BadPaddingException:给出com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)的com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)的最终块没有正确填充.sun.crypto.provider.DESCipher.engineDoFinal(DashoA13*..)在javax.crypto.Cipher.doFinal(DashoA13*..)at ...

这是我的代码:

public static PrivateKey readPrivateKeyFromFile(File file, String chaveSecreta) {
    try {
        SecureRandom r = new SecureRandom(chaveSecreta.getBytes());
        KeyGenerator keyGen = KeyGenerator.getInstance("DES");
        keyGen.init(56, r);
        Key key = keyGen.generateKey();

        byte[] privateKeyBytes = decryptPKFile(file, key);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        PrivateKey privateKey = null;
        try {
            privateKey = keyFactory.generatePrivate(privateKeySpec);
        } catch (InvalidKeySpecException e) {
            JOptionPane.showMessageDialog(null, "Erro 01, tente mais tarde");
        }
        return privateKey;
    } catch (NoSuchAlgorithmException e) {
        JOptionPane.showMessageDialog(null, "Erro 02, tente mais tarde");
    }
    return null;
}

public static byte[] decryptPKFile(File file, Key key){
    try{
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        byte[] cipherText = readBytes(file);
        cipher.init(Cipher.DECRYPT_MODE, key);
        System.out.println(cipher);
        System.out.println(cipherText);
        byte[] text = cipher.doFinal(cipherText);
        return text;
    }catch(Exception e){
        e.printStackTrace();
        return null;
    }
}

public static byte[] readBytes(File file) {
    try {
        FileInputStream fs = new FileInputStream(file);
        byte content[] = new byte[(int) file.length()];
        fs.read(content);
        return content;
    } catch (FileNotFoundException e) {
        System.out.println("Arquivo não encontrado!");
        e.printStackTrace();
    } catch (IOException ioe) {
        System.out.println("Erro ao ler arquivo!");
        ioe.printStackTrace();
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

Maa*_*wes 8

您正尝试使用使用特定种子创建的随机数生成器解密密文.但是,您没有指定算法,并且算法也可能在内部更改.甚至知道Android会为某些版本生成完全随机的值.

你需要使用a SecretKeyFactory而不是a KeyGenerator.你当然需要8字节的密钥数据.在您的情况下检索此问题的唯一方法是在之前找到SecureRandom算法/实现并重新计算密钥.

现在任何密文都会用任何密钥解密.DES ECB仅提供(某种)机密性,而非完整性.问题是它会解密成垃圾.现在,如果您尝试从垃圾中删除填充,则可能会出现填充错误.

如果你"幸运" - 一次大约256次 - 你会得到一个结果.当解密的块以010202,即有效填充结束时,会发生这种情况.结果 - 当然 - 也是垃圾,但它不会以a结尾BadPaddingException.在您的情况下,SecureRandom实例可能会一遍又一遍地返回相同的不正确的值,因此这可能永远不会发生.

将来,请使用PBKDF2并输入编码密码.清楚地注意使用的字符编码,Java SE使用char数组的最低8位.永远不要使用,String.getBytes()因为默认编码可能因系统而异.

  • 我想这是因为我的系统.使用Windows时一切正常,但它无法在我的Mac上运行.猜猜你说的是String.getBytes(). (2认同)