【问题标题】:Decryption Given final block not padded properly error解密给定最终块未正确填充错误
【发布时间】:2015-03-28 21:56:18
【问题描述】:

我正在尝试从 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;



}

【问题讨论】:

    标签: java mysql sql encryption padding


    【解决方案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);
    }
    

    【讨论】:

    • 在整个程序中没有相同的密钥,或者你的意思是我不应该多次生成?另外,当我将加密文本直接放入 decrytPassword 方法时,它可以正常工作 idk
    • 如果加密和解密的密钥相同。那么最有可能我的第二点就是问题所在。
    • 我试过了,还是不行。这可能是我将它存储在数据库中的方式吗?这对它有什么影响吗?
    • 好吧,如果你没有正确写入字节数组,你也不能解密它。
    猜你喜欢
    • 1970-01-01
    • 2014-01-22
    • 2017-03-17
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 2018-08-17
    相关资源
    最近更新 更多