08 May 2016

ADD2 Test Eclipse - Aptech FPT 2016 - Validating and Encrypting Password Saving database Java Swing

 TEST ADD2  - Aptech FPT 2016




1 - Create database.

CREATE DATABASE contactinfo;

CREATE TABLE `contact` (
  `email` varchar(50) NOT NULL,
  `pass` varchar(30) NOT NULL,
  `phone` varchar(20) 
) ;

2 - DBConnection.java


Add library connect database
package controller;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBConnection {

 private static Connection conn;
 static final String DRIVER_JDBC = "com.mysql.jdbc.Driver";
 static final String DB_URL = "jdbc:mysql://localhost/contactinfo";
 static final String USER = "root";
 static final String PASS = "1234567";

 public static Connection getConnection() {
  try {
   Class.forName(DRIVER_JDBC);
   conn = DriverManager.getConnection(DB_URL, USER, PASS);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return conn;
 }
}





3 - View.java




Button send >> Validating



Button reset >> Reset


package view;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JTextField;

import model.Contact;
import model.ContactDAO;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JPasswordField;

public class Vew {

 private JFrame frmDesignPreviewexam;
 private JTextField txtEmail;
 private JTextField txtPhone;
 private JPasswordField txtPass;
 private JPasswordField txtCpass;

 /**
  * Launch the application.
  */
 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     Vew window = new Vew();
     window.frmDesignPreviewexam.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }

 /**
  * Create the application.
  */
 public Vew() {
  initialize();
 }

 /**
  * Initialize the contents of the frame.
  */
 private void initialize() {
  frmDesignPreviewexam = new JFrame();
  frmDesignPreviewexam.setTitle("Design Preview [Exam04]");
  frmDesignPreviewexam.setBounds(100, 100, 450, 278);
  frmDesignPreviewexam.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frmDesignPreviewexam.getContentPane().setLayout(null);
  
  txtEmail = new JTextField();
  txtEmail.setBounds(197, 38, 167, 20);
  frmDesignPreviewexam.getContentPane().add(txtEmail);
  txtEmail.setColumns(10);
  
  txtPhone = new JTextField();
  txtPhone.setColumns(10);
  txtPhone.setBounds(197, 131, 167, 20);
  frmDesignPreviewexam.getContentPane().add(txtPhone);
  
  JButton btnSend = new JButton("Send");
  btnSend.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    //Validating email, pass, is phone not null
    if(txtEmail.getText().isEmpty()){
     JOptionPane.showMessageDialog(null, "Email not null \n Enter email !");
    }else if(txtPass.getText().isEmpty()){
     JOptionPane.showMessageDialog(null, "Password not null \n Enter Password ! ");
    }else if(txtCpass.getText().isEmpty()){
     JOptionPane.showMessageDialog(null, "Confirm password not null \n Enter Confirm password ");
    }else if(txtPhone.getText().isEmpty()){
     JOptionPane.showMessageDialog(null, "Phone number not null \n Enter Phone number");
    }else if(txtPass.getText() != txtCpass.getText()){
     //Action do some thing setter to contact
     Contact contact = new Contact();
     if(txtPass.getText().equals(txtCpass.getText())){
      contact.setEmail(txtEmail.getText());
      contact.setPhone(txtPhone.getText());
      contact.setPass(txtPass.getText());
      JOptionPane.showMessageDialog(null, "Send to database successfully!");
      
      ContactDAO contactDao = new ContactDAO();
      contactDao.addContact(contact);
     }else{
      JOptionPane.showMessageDialog(null, "Confirm password Wrong!");
     }
    }
   }
  });
  btnSend.setBounds(152, 185, 89, 23);
  frmDesignPreviewexam.getContentPane().add(btnSend);
  
  JButton btnReset = new JButton("Reset");
  btnReset.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    txtEmail.setText("");
    txtPass.setText("");
    txtCpass.setText("");
    txtPhone.setText("");
   }
  });
  btnReset.setBounds(275, 185, 89, 23);
  frmDesignPreviewexam.getContentPane().add(btnReset);
  
  JLabel lblPassword = new JLabel("Password");
  lblPassword.setBounds(44, 72, 111, 14);
  frmDesignPreviewexam.getContentPane().add(lblPassword);
  
  JLabel lblEmail = new JLabel("Email");
  lblEmail.setBounds(44, 41, 111, 14);
  frmDesignPreviewexam.getContentPane().add(lblEmail);
  
  JLabel lblConfirmPassword = new JLabel("Confirm Password");
  lblConfirmPassword.setBounds(44, 103, 111, 14);
  frmDesignPreviewexam.getContentPane().add(lblConfirmPassword);
  
  JLabel lblPhoneNumber = new JLabel("Phone Number");
  lblPhoneNumber.setBounds(44, 134, 111, 14);
  frmDesignPreviewexam.getContentPane().add(lblPhoneNumber);
  
  txtPass = new JPasswordField();
  txtPass.setBounds(197, 69, 167, 20);
  frmDesignPreviewexam.getContentPane().add(txtPass);
  
  txtCpass = new JPasswordField();
  txtCpass.setBounds(197, 100, 167, 20);
  frmDesignPreviewexam.getContentPane().add(txtCpass);
 }
}

4 - Contact.java  

>> Set and Get  Constructor
package model;

public class Contact {

 private String email;
 private String pass;
 private String phone;

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public String getPass() {
  return pass;
 }

 public void setPass(String pass) {
  this.pass = pass;
 }

 public String getPhone() {
  return phone;
 }

 public void setPhone(String phone) {
  this.phone = phone;
 }

 public Contact() {
  super();
  // TODO Auto-generated constructor stub
 }

}

5 - ContactDAO.java  

>> Encrypt MD5  & Insert




package model;

import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import controller.DBConnection;

public class ContactDAO {
 
 private Connection conn;
 private PreparedStatement stmt;
 
 public ContactDAO() {
  conn = DBConnection.getConnection();
 }
 
 private static String key = "1234abcd";

 private static String encrypt(String message) throws Exception {

  Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
  DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
  SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
  SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
  IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
  cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
  return toHexString(cipher.doFinal(message.getBytes("UTF-8")));
 }

 private static String toHexString(byte b[]) {
  StringBuffer hexString = new StringBuffer();
  for (int i = 0; i < b.length; i++) {
   String plainText = Integer.toHexString(0xff & b[i]);
   if (plainText.length() < 2)
    plainText = "0" + plainText;
   hexString.append(plainText);
  }
  return hexString.toString();
 }
 
 public void addContact(Contact contact){
  String sql ="Insert Into contact Values(?,?,?)";
  try {
   stmt = conn.prepareStatement(sql);
   stmt.setString(1, contact.getEmail());
   stmt.setString(2, encrypt(contact.getPass()));
   stmt.setString(3, contact.getPhone());
   
   stmt.executeUpdate();
   
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 
 
}


Làm theo cách 2


Database Connection
Java 2016
package md5Encrypt;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBUtil {
 private static Connection conn;
 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
 static final String DB_URL = "jdbc:mysql://localhost/testencryptmd5";
 static final String DB_USER = "root";
 static final String DB_PASS = "1234567";

 public static Connection getConnection() {
  if (conn != null) {
   return conn;
  } else {

   try {
    Class.forName(JDBC_DRIVER);
    conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
   } catch (Exception e) {
    e.printStackTrace();
   }

   return conn;
  }
 }

}

Program
Java 2016
package md5Encrypt;

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class Program {

 private JFrame frame;
 private JTextField txtEmail;
 private JPasswordField txtPass;
 private JPasswordField txtPassConfig;
 private JTextField txtPhone;

 /**
  * Launch the application.
  */
 private PreparedStatement stmt;
 private Connection conn;
 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     Program window = new Program();
     window.frame.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }

 /**
  * Create the application.
  */
 public Program() {
  initialize();
  try {
   conn = DBUtil.getConnection();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

  private static String key = "1234abcd";
  private static String encrypt(String message) throws Exception {

    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
    IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
    return toHexString(cipher.doFinal(message.getBytes("UTF-8")));
   }

   private static String toHexString(byte b[]) {
    StringBuffer hexString = new StringBuffer();
    for (int i = 0; i < b.length; i++) {
     String plainText = Integer.toHexString(0xff & b[i]);
     if (plainText.length() < 2)
      plainText = "0" + plainText;
     hexString.append(plainText);
    }
    return hexString.toString();
   }
 /**
  * Initialize the contents of the frame.
  */
 private void initialize() {
  frame = new JFrame();
  frame.setBounds(100, 100, 450, 300);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.getContentPane().setLayout(null);
  
  JLabel lblSend = new JLabel("Send  Your Contact");
  lblSend.setFont(new Font("Tahoma", Font.BOLD, 30));
  lblSend.setBounds(53, 11, 371, 34);
  frame.getContentPane().add(lblSend);
  
  txtEmail = new JTextField();
  txtEmail.setBounds(158, 68, 190, 20);
  frame.getContentPane().add(txtEmail);
  txtEmail.setColumns(10);
  
  JLabel lblEmail = new JLabel("Email:");
  lblEmail.setBounds(40, 71, 46, 14);
  frame.getContentPane().add(lblEmail);
  
  txtPass = new JPasswordField();
  txtPass.setBounds(158, 99, 190, 20);
  frame.getContentPane().add(txtPass);
  
  JLabel lblPassword = new JLabel("Password");
  lblPassword.setBounds(40, 102, 65, 14);
  frame.getContentPane().add(lblPassword);
  
  txtPassConfig = new JPasswordField();
  txtPassConfig.setBounds(158, 132, 190, 20);
  frame.getContentPane().add(txtPassConfig);
  
  JLabel lblConfigPassword = new JLabel("Config Password");
  lblConfigPassword.setBounds(40, 135, 108, 14);
  frame.getContentPane().add(lblConfigPassword);
  
  JLabel lblPhoneNumber = new JLabel("Phone number:");
  lblPhoneNumber.setBounds(40, 171, 108, 14);
  frame.getContentPane().add(lblPhoneNumber);
  
  txtPhone = new JTextField();
  txtPhone.setBounds(157, 168, 191, 20);
  frame.getContentPane().add(txtPhone);
  txtPhone.setColumns(10);
  
  JButton btnSend = new JButton("Send ");
  btnSend.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    if(txtEmail.getText().equals("")){
     JOptionPane.showMessageDialog(null, "Please enter email!");
    }else if(txtPhone.getText().equals("")){
     JOptionPane.showMessageDialog(null, "Please enter number phone!");
    }else if(txtPass.getText().equals("")){
     JOptionPane.showMessageDialog(null, "Please enter pass!");
    }else if(txtPassConfig.getText().equals("")){
     JOptionPane.showMessageDialog(null, "Please enter pass config!");
    }else if(txtPass.getText().equals(txtPassConfig.getText())!= true){
     JOptionPane.showMessageDialog(null, "Pass Config Wrong!!");
    }else{
     String sql = "INSERT INTO `testencryptmd5`.`manager` ( `email`, `pass`, `phone`) VALUES ( ?, ?, ?)";
     try {
      stmt = conn.prepareStatement(sql);
      stmt.setString(1, txtEmail.getText());
      stmt.setString(2, encrypt(txtPass.getText()));
      stmt.setString(3, txtPhone.getText());
      stmt.executeUpdate();
     } catch (Exception e2) {
      e2.printStackTrace();
     }
      JOptionPane.showMessageDialog(null, "sent successfully!");
    }
   }
  });
  btnSend.setBounds(100, 211, 89, 23);
  frame.getContentPane().add(btnSend);
  
  JButton btnReset = new JButton("Reset");
  btnReset.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    txtEmail.setText(null);
    txtPass.setText(null);
    txtPassConfig.setText(null);
    txtPhone.setText(null);
   }
  });
  btnReset.setBounds(259, 211, 89, 23);
  frame.getContentPane().add(btnReset);
 }
}




0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang