哈希到数据库

时间:2018-04-08 11:13:03

标签: java hash

我正在研究我的小项目,我有一个问题要问,因为我无法弄明白。基本上我使用netbeans和im创建登录/注册验证并将细节保存到数据库,我试图在有人注册时实现散列函数,以便文本不会被保存为数据库中的纯文本。

我已经尝试了很少的教程来实现我的项目中的哈希,但我不能这样做。任何提示都是受欢迎的。

这是注册表格:

    String name = this.name.getText();
    String lastname = this.lastname.getText();
    String email = this.email.getText();
    String pass = new String(password.getPassword());
    String repass = this.repassword.getText();

    boolean valid = true;
    // Declaraction on name                  
    if (name.length() > 15 || name.length() < 3){
        JOptionPane.showMessageDialog(null, "Please enter your correct name", "Incorrect details", JOptionPane.ERROR_MESSAGE);
        valid = false;
    }
    if(name.equals("")){
        JOptionPane.showMessageDialog(null, "Name can't be empty", "Incorrect details", JOptionPane.ERROR_MESSAGE);
        valid = false;
    }
    //Declaraction on surname
    if (lastname.length() > 20 || lastname.length() < 3){
        JOptionPane.showMessageDialog(null, "Please enter your correct surname", "Incorrect details", JOptionPane.ERROR_MESSAGE);
        valid = false;
    }
    if(lastname.equals("")){
        JOptionPane.showMessageDialog(null, "Surname can't be empty", "Incorrect details", JOptionPane.ERROR_MESSAGE);
        valid = false;
    }
    //Declaraction of email
    if (!(Pattern.matches("^[a-zA-Z0-9-_]+[@]+[gmail]+[.]+[com]+$", this.email.getText()))){
        JOptionPane.showMessageDialog(null, "Please enter a Gmail email", "Incorrect details", JOptionPane.ERROR_MESSAGE);
        valid = false;
    }
    //Declaraction of password / repeat password
    if(pass.length() > 15 || pass.length() < 8){
        JOptionPane.showMessageDialog(null, "Password should be less than 15 and more than 8 characters in length.", "Incorrect details", JOptionPane.ERROR_MESSAGE);
        valid = false;
    }
    if(pass.contains(name)){
        JOptionPane.showMessageDialog(null, "Password Should not contain same words as your name", "Incorrect details", JOptionPane.ERROR_MESSAGE);
        valid = false;
    }
    String upperCaseChars = "(.*[A-Z].*)";
    if(!pass.matches(upperCaseChars )){
        JOptionPane.showMessageDialog(null, "Password should contain atleast one upper case alphabet", "Incorrect details", JOptionPane.ERROR_MESSAGE);
        valid = false;
    }
    String lowerCaseChars = "(.*[a-z].*)";
    if(!pass.matches(lowerCaseChars )){
        JOptionPane.showMessageDialog(null, "Password should contain atleast one lower case alphabet", "Incorrect details", JOptionPane.ERROR_MESSAGE);
        valid = false;
    }
    String numbers = "(.*[0-9].*)";
    if (!pass.matches(numbers )){
        JOptionPane.showMessageDialog(null, "Password should contain atleast one number.", "Incorrect details", JOptionPane.ERROR_MESSAGE);
        valid = false;
    }
    if (!pass.matches(repass)){
        JOptionPane.showMessageDialog(null, "Passwords dont match.", "Incorrect details", JOptionPane.ERROR_MESSAGE);
        valid = false;
    }
    if(valid){
        User u = new User();
        u.setID(0);
        u.setName(name);
        u.setLastname(lastname);
        u.setEmail(email);
        u.setPassword(pass);
        u.setRepassword(repass);

        UserController uc = new UserController();

        int res = uc.createAccount(u);

        if (res > 0) {
            JOptionPane.showMessageDialog(null, "You have been Registered");

        }
        else {
            JOptionPane.showMessageDialog(null, "Unable to Register", "Incorrect details", JOptionPane.ERROR_MESSAGE);
        }
    }

所有这一切都发生在用户点击gui上的“注册”按钮后。

保存到数据库+ retrives的完整UserController在这里:

public class UserController extends User{    
Database db;
Connection con;
PreparedStatement pst;

public UserController() {
    super();
    db = new Database();
    con = db.getConnection();
}

public int createAccount(User u) {
    int res = 0;
    String sql = "";

    try {
        sql = "INSERT INTO user(`id`,`name`,`lastname`,`email`,`password`,`repassword`) VALUES(NULL, ?, ?, ?, ?, ?)";
        pst = con.prepareStatement(sql);

        pst.setString(1, u.getName());
        pst.setString(2, u.getLastname());
        pst.setString(3, u.getEmail());
        pst.setString(4, u.getPassword());
        pst.setString(5, u.getRepassword());

        res = pst.executeUpdate();

    } catch (SQLException e) {
        System.out.println(e.getMessage());
    }

    return res;
}    
private String md5(char[] c){
    try{
    MessageDigest digs = MessageDigest.getInstance("MD5");

    digs.update(new String(c).getBytes("UTF8"));
    String str = new String(digs.digest());
    return str;        
    }
    catch(Exception ex){
        return "";
    }
}

public boolean checkLogin(User u) {

    String sql = "";
    ResultSet rs = null;

    try {
        sql = "SELECT * FROM user WHERE email = ? and password = ?";
        pst = con.prepareStatement(sql);

        pst.setString(1, u.getEmail());
        pst.setString(2, u.getPassword());

        rs = pst.executeQuery();

        if (rs.next()) {
            return true;
        } else {
            return false;
        }


    } catch(SQLException e) {
        System.out.println(e.getMessage());
    }


    return false;


 }
}

我应该实际实现它的任何提示,或者任何关于如何实现它的实际提示都将会被欣赏,只是再次说明,我使用netbeans进行开发。谢谢大家。

1 个答案:

答案 0 :(得分:0)

您可以使用此方法在将密码保存到数据库之前对其进行哈希处理

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class PasswordUtils {



 private final static String SALT = "your_salt_string_here";


  /**
   * Hash a password with SHA-1 algorithm and salt.
   * 
   * @param password  The password to encrypt.
   * @return            The hexadecimal number representation of the encrypted password.
   */
  public static String hashPassword(String password) {
    String result = null;
    MessageDigest md;

    try {
        md = MessageDigest.getInstance("SHA-1");
        byte[] hash1 = md.digest(password.getBytes());

        md.reset();
        byte[] hash2 = md.digest(hash1);

        md.reset();
        md.update(SALT.getBytes());
        md.update(hash2);

        byte[] digest = md.digest();
        for (int i = 0; i < digest.length; i++) {
            digest[i] = (byte) (digest[i] ^ hash1[i]);
        }   

        result = String.format("%0" + (digest.length << 1) + "x",new BigInteger(1,digest));     

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    return result;
  }
}