how to a program such that i want to store username and encrypted password in database and when i retreive from database i should get username and decrypted password. plz im waiting for ur reply. thank in advance.
The given code will allow the user to enter username and password. This password is then encrypted and insert into the database along with username. If you user want to get the encrypted password in its decrypted form then you can easily get it from the database.
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.sql.*; import java.security.*; import javax.crypto.*; class Login extends JFrame implements ActionListener { JButton SUBMIT; JPanel panel; JLabel label1,label2; final JTextField text1,text2; private static String algorithm = "DESede"; private static Key key = null; private static Cipher cipher = null; private static byte[] encrypt(String input)throws Exception { cipher.init(Cipher.ENCRYPT_MODE, key); byte[] inputBytes = input.getBytes(); return cipher.doFinal(inputBytes); } private static String decrypt(byte[] encryptionBytes)throws Exception { cipher.init(Cipher.DECRYPT_MODE, key); byte[] recoveredBytes = cipher.doFinal(encryptionBytes); String recovered = new String(recoveredBytes); return recovered; } Login() { label1 = new JLabel(); label1.setText("Username:"); text1 = new JTextField(15); label2 = new JLabel(); label2.setText("Password:"); text2 = new JPasswordField(15); SUBMIT=new JButton("SUBMIT"); panel=new JPanel(new GridLayout(3,1)); panel.add(label1); panel.add(text1); panel.add(label2); panel.add(text2); panel.add(SUBMIT); add(panel,BorderLayout.CENTER); SUBMIT.addActionListener(this); } public void actionPerformed(ActionEvent ae) { try{ String uname=text1.getText(); String pass=text2.getText(); key = KeyGenerator.getInstance(algorithm).generateKey(); cipher = Cipher.getInstance(algorithm); String input = pass; byte[] encryptionBytes = encrypt(input); String passw=new String(encryptionBytes); String connectionURL = "jdbc:mysql://localhost:3306/test"; Connection con=null; Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(connectionURL, "root", "root"); PreparedStatement ps = con.prepareStatement("INSERT INTO login(username,password) VALUES(?,?)"); ps.setString(1,uname); ps.setString(2,passw); int i = ps.executeUpdate(); ps.close(); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("Select * from login where username='"+uname+"'"); String str=""; if(rs.next()){ str=rs.getString("password"); } JOptionPane.showMessageDialog(null,"Your password is: "+decrypt(str.getBytes())); } catch(Exception e){} } public static void main(String arg[])throws Exception { try { Login frame=new Login(); frame.setSize(300,100); frame.setVisible(true); } catch(Exception e) {JOptionPane.showMessageDialog(null, e.getMessage());} } }