将密码保存到derby或sql数据库

时间:2016-08-25 00:38:28

标签: java sql passwords

我有一个应用程序要求我有一个密码终端。我正在使用JPassword字段(JAVA)。现在我想要的是能够以加密形式将密码保存在数据库中,这是我无法读取的,当我检索比较时,两者应该相等但是眼睛保持不可读。请问我该怎么做呢,因为目前使用jpassword,我转换它,当我保存它时。当我保存而不转换时,我无法比较,因为值不同。我希望能够比较数据库和GUI中的密码,而不会在数据库中看到密码。请帮忙。

以下是我的代码:

 package trackme;

    /**
     *
     * @author kels
     */
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.sql.*;
    import java.util.Arrays;

    /**
     *
     * @author kels
     */
    public class Login  extends JFrame implements ActionListener, ItemListener{

            DBOperator login;
    Statement stat;
    ResultSet rs;
    Connection con;

    String comparestring="Registration";  int getint=4;
     java.sql.Time t = new java.sql.Time(new java.util.Date().getTime());
               java.sql.Date dt = new java.sql.Date(new java.util.Date().getTime());
       private String dbtxt = null, getpassword, username=null, gettype=null;
    //private String gettype="";
         //name components
        JLabel lbllogin = new JLabel("Password: ");
        final    JCheckBox cbshow = new JCheckBox("Show Password");
        JPasswordField txtlogin = new JPasswordField(10);

        JLabel lblusername = new JLabel("UserName:");
        JTextField txtusername = new JTextField(10);


          JButton btnlogin = new JButton("Login");
          JLabel label = new JLabel("");

          //create containers
          JPanel loginpanel = new JPanel();
          JPanel wrappanel = new JPanel();
          JPanel finalpanel = new JPanel();
          JPanel btnpanel=new JPanel();
          JPanel showpanel = new JPanel();
            JPanel usernamepanel = new JPanel();

        @SuppressWarnings("LeakingThisInConstructor")
          public Login(){
              super("Login");
              setResizable(false);

              setLocation(250, 260);
              setSize(250,170);
              Container pane = getContentPane();

              //set Layout Managers
             GridLayout grid = new GridLayout(4,1);
              BorderLayout bord = new BorderLayout();

              //set the managers to the panels
            wrappanel.setLayout(grid);
              pane.setLayout(bord);

              //add components
              usernamepanel.add(lblusername);
              usernamepanel.add(txtusername);
              loginpanel.add(lbllogin);
              loginpanel.add(txtlogin);
              wrappanel.add(usernamepanel);
            wrappanel.add(loginpanel);
               finalpanel.add(wrappanel);
               wrappanel.add(showpanel);
                showpanel.add(cbshow);
               btnpanel.add(btnlogin);
               wrappanel.add(label);
               pane.add(btnpanel, BorderLayout.SOUTH);
               pane.add(finalpanel, BorderLayout.CENTER);

               setContentPane(pane);
               setVisible(true);
              btnlogin.addActionListener(this);
              cbshow.addItemListener(this);

                txtlogin.setEchoChar('*');
          }

        @Override
          public void actionPerformed(ActionEvent ae){
              Object source = ae.getSource();
               login = new DBOperator();
            stat = login.getStatement();
            // PreparedStatement preparedStatement;
             String status = ""; String getstatus="Loggedout"; String getusername=""; String gettypedb="";
            try{
            if(source == btnlogin){

                java.sql.Time  dbtime = null; java.sql.Date dbdate = null; 
              char [] paswrdtxt, passchar;
           paswrdtxt =txtlogin.getPassword();
            getpassword= String.valueOf(paswrdtxt);

            String getstatustrim="";
               //making sure user in not logged in
              rs=stat.executeQuery("SELECT USERNAMEDB,PASSWORD,TYPE FROM PWORD WHERE PASSWORD="
                      + ""+"'"+getpassword+"'" +" AND USERNAMEDB="+"'"+txtusername.getText()+"'"+"");

               while(rs.next()){
                   username=rs.getString("Usernamedb");
                 dbtxt=rs.getString("Password");
                 gettype=rs.getString("Type");

               }
               rs.close();

                if(getpassword.equals(dbtxt) && txtusername.getText().equals(username)){

                    /*do insert to logindb here and check status first to know if logged in or out
                    if loggedin error cause u cant login in while logged in and u can logout when not logged in
                    */
                            rs = stat.executeQuery("SELECT STATUS FROM LOGINDB WHERE  LOGINDATE="+"'"+dt+"'" 
                                    +" AND USERNAME="+"'"+txtusername.getText()+"'"+"");
              while(rs.next()){

                status=rs.getString("Status");

               }
               rs.close();
              }//end if comparison            
            }//end btnlogin

             stat.close();
          }//end try
          catch(SQLException ex){
              System.out.println(ex.toString() + "no deal");
          }

          }
        public static void main(String[] args){
            Login lm = new Login();      

        }
    }

提前致谢

1 个答案:

答案 0 :(得分:0)

我终于得到了我的问题的答案。 经过大量研究后,我使用Java加密API将它们整合在一起。 我感谢上帝和你的建议@ cricket_007 以下是我需要的代码片段:

import java.security.Key;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


 private static final String ALGORITHM = "AES";
private static final String KEY = "1Hbfh667adfDEJ78";

 String encryptedPassword = null;  String encryptname = null;
              try {
                  encryptedPassword = encrypt(getpassword);
                  encryptname = encrypt(ppword);
              } catch (Exception ex) {
                  Logger.getLogger(Tester.class.getName()).log(Level.SEVERE, null, ex);
              }

public  String encrypt(String value) throws Exception
{
Key key = generateKey();
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte [] encryptedByteValue = cipher.doFinal(value.getBytes("utf-8"));
String encryptedValue64 = new BASE64Encoder().encode(encryptedByteValue);
return encryptedValue64;
}

private  Key generateKey() throws Exception
{
Key key = new SecretKeySpec(KEY.getBytes(),ALGORITHM);
return key;
}

由于