解密给定最终块未正确填充错误

时间:2015-01-29 15:42:34

标签: java mysql sql encryption padding

我正在尝试解密来自MySQL数据库的密码,该数据库以字节存储为varbinary。当我通过解密算法放置它时,我得到给定的最终块未正确填充错误,即使它在我没有数据库的情况下测试时也能正常工作。我不知道哪里出错了。

以下是我的代码:

public boolean selectCheckUser(String username, String password) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException, Exception{

    Key symKey = KeyGenerator.getInstance(algorithm).generateKey();
    Cipher c = Cipher.getInstance(algorithm);
    String checkUsername = null;
    String checkPassword = null;
    byte[] cipherPassword = null;
    boolean check = false;
    try{
        stmt = (PreparedStatement) connect.prepareStatement("SELECT username, password FROM userdetails WHERE username = ?");
        stmt.setString(1,username);
        ResultSet data = stmt.executeQuery();

        if(data.next()){
            checkUsername = data.getString("username");
        }

        cipherPassword = data.getBytes("password");
        System.out.println(data.getBytes("password"));

        checkPassword = Encrypt.decryptPassword(cipherPassword, symKey, c);

这是解密算法:

public static String decryptPassword(byte[] encryptionBytes, Key pkey, Cipher c) throws InvalidKeyException,
BadPaddingException, IllegalBlockSizeException, Exception {


       c.init(Cipher.DECRYPT_MODE, pkey);
       byte[] decrypt = c.doFinal(encryptionBytes);
       String decrypted = new String(decrypt);
       return decrypted;



}

1 个答案:

答案 0 :(得分:-1)

问题出在这里。您在这里生成一个新密钥。您需要使用与加密数据相同的密钥。根据算法,可能有公钥和私钥。

Key symKey = KeyGenerator.getInstance(algorithm).generateKey();

byte[] decrypt = c.doFinal(encryptionBytes);

doFinal可以返回一个字节数组,但它也可能需要运行多次才能完成,所以你需要做的就是遍历它。

byte[] decrypt = c.doFinal(encryptionBytes);
while(decrypt[decrypt.length] != 0) {
    decrypt = c.doFinal(encryptionBytes);
}
相关问题