Kelly Blue Kelly Blue - 3 months ago 14
Java Question

Saving passwords to derby or sql database

I have an application that requires me to have a password terminal. I am using

JPassword
field (JAVA). Now what I want is for me to be able to save the password in database in encrypted form that I cannot read and when I retrieve for comparison both should be equal but to the eye stay unreadable. please how do I go about this because presently, using
jpassword
, I convert it and when I save it is seen. when I save it without converting I am unable to compare because the values are different. I want to be able to compare the passwords from database and
GUI
without the password being visible in database. Please help.

Below is my code:

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();

}
}


Thanks in advance

Answer

I have finally gotten the answer to my question. After much research I used the Java crypto API to put it all together. I thank God for this and your suggestion @cricket_007 Below is are the code fragments of what I needed:

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;
}

Thanks