在Java中,没有正确地从MySQL数据库中解密密码

时间:2015-10-18 11:23:43

标签: java mysql encryption

我有一个登录屏幕,每次用户登录密码都会在MySQL数据库中加密,然后在解密后恢复正常并被接受验证。他们系统没有问题地对数据进行加密,但是当它解密时,它会错误地进行加密并且不起作用。

加密格式为byte,但MySQL中的密码格式为VARCHAR。我假设这是造成问题的原因。格式化数据类型的正确方法是什么,以便密码被正确解密,因为MySQL没有byte格式?

以下是正在发生的事情的一个例子:

enter image description here

密码为Pass123,消息对话框中的第二行显示密码的解密方式。然后顶行显示如何从MySQL解密密码

以下是此功能的编码:

try
{ 
    Class.forName("com.mysql.jdbc.Driver");
    //connection for database
    Connection conn = (Connection)
            //root and username and password for access to the database
    DriverManager.getConnection("jdbc:mysql://localhost:3306/salventri","root","password");
    //create the statement that will be used
    Statement stmt=conn.createStatement();
    //executes the statement
    ResultSet rs = stmt.executeQuery(getCat); 

    int user = Integer.parseInt(txtUsername.getText());
    String pwd = new String(txtPassword.getPassword());
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    SecretKeySpec key = new SecretKeySpec(keyBytes, "DES"); 
    IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
    cipher = Cipher.getInstance("DES/CTR/NoPadding", "BC");



    while (rs.next())
    {
        int uname = rs.getInt("username");
        //Username is the coloumn name in the database table 
        String password = rs.getString("password");
        byte [] pass = password.getBytes();
        cipherText = pass;
        cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
        byte[] plainText = new byte[cipher.getOutputSize(ctLength)];
        int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0);
        ptLength += cipher.doFinal(plainText, ptLength);
        String upassword = String.valueOf(ptLength);


        if (user == uname) 
        {
            JOptionPane.showMessageDialog(null, "username  " + uname + " Password " + cipherText + "\n password as string " + password);
            //...
        }
    }
}
catch (Exception e)
{
    //exception handled
    JOptionPane.showMessageDialog(null, e);
}

0 个答案:

没有答案