Java MD5加密实战(账号登录注册系统)

程序框架

程序框架如图所示:
Java MD5加密实战(账号登录注册系统)_第1张图片

代码展示:

Main方法:

package com.jd.test;

import java.util.ArrayList;
import java.util.Scanner;
import java.util.UUID;

import com.jd.tool.MD5Tool;
import com.jd.tool.db.DBLink;
/*
 * 问题:当DBA(数据库管理员)登录数据库查看时可以看到所有人的账户密码,有可能造成泄密
 * 解决方法:MD5加密
 * 
 * */
public class Main {

	public static void main(String[] args) {
			System.out.println("*********************************");
		    System.out.println("*\t\t\t\t*");
		    System.out.println("*\t欢迎使用账号登录页面\t*");
		    System.out.println("*\t\t\t\t*");
		    System.out.println("*********************************");
		    while (true) {
		      menu();
		    }
	    }

		@SuppressWarnings("unlikely-arg-type")
		static void menu() {
		    System.out.println("1、注册");//用户名 密码  确认密码
		    System.out.println("2、登录");//用户名和密码
		    System.out.println("3、退出");//System.exit(0)结束
		    System.out.println("请输入操作,以Enter键结束:");
		    Scanner scanner = new Scanner(System.in);
		    int option  = scanner.nextInt();
		    switch (option) {
		    	case 1:{
		    		System.out.println("请输入用户名:");
		    		String userName = scanner.next();
		    		System.out.println("请输入密码:");
		    		String password = scanner.next();
		    		System.out.println("请再次确认密码:");
		    		String rePassword = scanner.next();
		    		String sql = "select id from user_info where user_name = ?";
		    		if(new DBLink().exist(sql, userName)) {
		    			System.out.println("用户名被占用,操作终止!");
		    			return;
		    		}
		    		if(!password.equals(rePassword)) {
		    			System.out.println("两次密码不同,操作终止!");
		    			return;
		    		}
		    		String id = UUID.randomUUID().toString();
		    		password = MD5Tool.encrypt(password);
		    		sql = "insert into user_info (id,user_name,password) values('"+id+"',?,?)";
		    		if(new DBLink().update(sql, userName,password)) {
		    			System.out.println("注册成功!");
		    			return;
		    		}
		    		System.out.println("注册失败!");
			    	break;
		    	}
		    	  
		    	case 2:{
		    		System.out.println("请输入用户名:");
		    		String userName = scanner.next();
		    		System.out.println("请输入密码:");
		    		String password = scanner.next();
		    		password = MD5Tool.encrypt(password);
		    		String sql = "select id from user_info where user_name = ? and password = ?";
		    		if(new DBLink().exist(sql, userName , password)) {
		    			System.out.println("登录成功!");
		    			return;
		    		}
		    		System.out.println("登陆失败!");
		    		break;
		    	}

		        case 3:{
		        	System.out.println("退出系统");
		        	System.exit(0);
		        }
		        default:
		        	System.out.println("I'm Sorry,there is not the "+option+" option,please try again.");
		      }
		}
}

MD5Tool:

package com.jd.tool;

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

public class MD5Tool {
	
	public static String encrypt(String password) {
		byte[] bytes = null;
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.update(password.getBytes());//鍔犲瘑
			bytes = messageDigest.digest();//鑾峰緱鍔犲瘑缁撴灉
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		String result = new BigInteger(1, bytes).toString(16);// 灏嗗姞瀵嗗悗鐨勬暟鎹浆鎹负16杩涘埗鏁板瓧
		// 鐢熸垚鏁板瓧鏈弧32浣嶏紝鍒欏墠闈㈣ˉ0
		for (int i = 0; i < 32 - result.length(); i++) {
			result = "0" + result;
		}
		return result;
	}
}

DBlink:

package com.jd.tool.db;
/**
 *    /** + enter 快速创建类或方法的注释格式
 */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;

/**
*数据库管理类
*
* @author WangJiaqi
*/
public class DBLink {
	
	/**
	 * 使用log4jar包使得错误类型存入文件夹中
	 */
	private Logger logger = Logger.getLogger(DBLink.class);
	
	/**
	 *获取数据库链接
	 *
	 * @author WangJiaqi
	 */
	private Connection getConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");//加载驱动
			String url = "jdbc:mysql://127.0.0.1:3306/test";
			return DriverManager.getConnection(url, "root", "root");//获取连接
		} catch (Exception e) {
			logger.debug(e.getMessage(),e);
		}
		return null;
	}
	
	/**
	 *判断SQL能否查出数据
	 *
	 * @author WangJiaqi
	 */
	public boolean exist(String sql) {
	    Connection connection = null;
	    Statement statement =null;
	    ResultSet resultSet=null;
	    try {
	      connection = getConnection();
	      statement = connection.createStatement();
	      resultSet= statement.executeQuery(sql);//执行sql,将查询的数据存到ResultSet类型的变量中
	      return resultSet.next();
	    } catch (Exception e) {
	    	logger.debug(e.getMessage(),e);
	    }finally {
	    	close(resultSet,statement,connection);
	     }
	    return false;
	  }
	
	/**
	 *判断SQL能否查出数据
	 *
	 * @author WangJiaqi
	 */
	public boolean exist(String sql,Object ...params) {
	    Connection connection = null;
	    PreparedStatement preparedStatement =null;
	    ResultSet resultSet=null;
	    try {
	      connection = getConnection();
	      preparedStatement = connection.prepareStatement(sql);
	      for (int i = 0; i < params.length; ++i) {
			preparedStatement.setObject(i + 1, params[i]);
		}
		resultSet= preparedStatement.executeQuery();//执行sql,将查询的数据存到ResultSet类型的变量中
	      return resultSet.next();
	    } catch (Exception e) {
	    	logger.debug(e.getMessage(),e);
	    }finally {
	    	close(resultSet,preparedStatement,connection);
	     }
	    return false;
	}
	
	/**
	 *查询数据
	 *
	 * @author WangJiaqi
	 */
	public void select(String sql,IRowMapper rowMapper) {//接口无法创建对象,所以rowMapper参数一定指向IRowMapper接口实现类对象
	    Connection connection = null;					//此处的rowMapper就是一个形参,到时候接口实现类里的实参再传给它
	    Statement statement =null;
	    ResultSet resultSet=null;
	    try {
	    	connection = getConnection();
	    	statement = connection.createStatement();
	        resultSet= statement.executeQuery(sql);//执行sql,将查询的数据存到ResultSet类型的变量中
	      rowMapper.rowMapper(resultSet);//因为rowMapper参数指向IRowMapper接口实现类对象,所以此处将调用接口实现类中所实现的rowMapper方法  多态
	    } catch (Exception e) {
	    	logger.debug(e.getMessage(),e);
	    }finally {
	    	close(resultSet,statement,connection);
	    }
	  }
	
	/**
	 *查询数据
	 *
	 * @author WangJiaqi
	 */
	public void select(String sql,IRowMapper rowMapper,Object ...params) {//接口无法创建对象,所以rowMapper参数一定指向IRowMapper接口实现类对象
	    Connection connection = null;									  //此处的rowMapper就是一个形参,到时候接口实现类里的实参再传给它
	    ResultSet resultSet=null;
	    PreparedStatement preparedStatement = null ;
	    try {
	    	connection = getConnection();
	    	preparedStatement = connection.prepareStatement(sql);
	    	for(int i = 0; i < params.length ; ++i) {
	    		preparedStatement.setObject(i+1,params[i]);
	    	}
	        resultSet= preparedStatement.executeQuery();
	        rowMapper.rowMapper(resultSet);//因为rowMapper参数指向IRowMapper接口实现类对象,所以此处将调用接口实现类中所实现的rowMapper方法  多态
	    } catch (Exception e) {
	    	logger.debug(e.getMessage(),e);
	    }finally {
	    	close(resultSet,preparedStatement,connection);
	    }
	  }
	
	/**
	 *修改(insert,update,和delete)数据
	 *
	 * @author WangJiaqi
	 */
	public boolean update(String sql) {
		Connection connection =null;
		Statement statement = null;
		try {
			connection = getConnection();
			statement = connection.createStatement();
			int result = statement.executeUpdate(sql);
			/*
			  statement.close();//如果上面代码出现异常,则该行代码及其下面代码无法执行,所以资源无法释放;比如sql语句语法错误,则statement和connection无法释放
		      connection.close();
		    */
			return result>0 ;
		}catch(Exception e) {
			logger.debug(e.getMessage(),e);
		}finally {
			close(statement,connection);
		}
		return false;
	}
	
	/**
	 *修改(insert,update,和delete)数据
	 *
	 * @author WangJiaqi
	 */
	public boolean update (String sql, Object ...params) {
		Connection connection = null;
		PreparedStatement prepareStatement = null;
		try {
			connection = getConnection();
			prepareStatement = connection.prepareStatement(sql);//sql是含有?的占位符
			for(int i = 0 ; i < params.length ;++i) {
				prepareStatement.setObject(i+1, params[i]);//为?赋值,有几个?数字就对应几
			}
			return prepareStatement.executeUpdate()>0;
		} catch (Exception e) {
			logger.debug(e.getMessage(),e);
		}finally {
			close(prepareStatement,connection);
		}
		return false;
	}

	/**
	 *释放资源
	 *
	 * @author WangJiaqi
	 */
	private void close(Statement statement,Connection connection) {
		try {
			if(statement!=null) {//由于异常statement没有赋值,statement异常,Eg:URL出错
				statement.close();	
			}
		} catch (SQLException e) {
			logger.debug(e.getMessage(),e);
		}
		try {
			if(connection!=null) {
				connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 释放资源
	 *
	 * @author WangJiaqi
	 */
	private void close(ResultSet resultSet,Statement statement,Connection connection) {
		try {
	        if(resultSet!=null) {
	          resultSet.close();
	        }
	      } catch (SQLException e) {
	    	  logger.debug(e.getMessage(),e);
	      }
	      close(statement,connection);
	}
}

IRowMapper:

package com.jd.tool.db;

import java.sql.ResultSet;

public interface IRowMapper {

	void rowMapper(ResultSet rs);
}

PropertiesTool.java

package com.jd.tool;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesTool {

	private static Properties properties = new Properties();
  
	static {
		InputStream inputStream = PropertiesTool.class.getClassLoader().getResourceAsStream("db.properties");//将db.properties变为javaIO流对象
		try {
			properties.load(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static String getValue(String key) {
		return properties.getProperty(key);
	}
}

db.properties:

db.username=root
db.password=root
db.url=jdbc:mysql://127.0.0.1:3306/test

log4j.properties:

#DEBUG\u8BBE\u7F6E\u8F93\u51FA\u65E5\u5FD7\u7EA7\u522B\uFF0C\u7531\u4E8E\u4E3ADEBUG\uFF0C\u6240\u4EE5ERROR\u3001WARN\u548CINFO \u7EA7\u522B\u65E5\u5FD7\u4FE1\u606F\u4E5F\u4F1A\u663E\u793A\u51FA\u6765
log4j.rootLogger=DEBUG,Console,RollingFile

#\u5C06\u65E5\u5FD7\u4FE1\u606F\u8F93\u51FA\u5230\u63A7\u5236\u53F0
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern= [%-5p]-[%d{yyyy-MM-dd HH:mm:ss}] -%l -%m%n
#\u5C06\u65E5\u5FD7\u4FE1\u606F\u8F93\u51FA\u5230\u64CD\u4F5C\u7CFB\u7EDFD\u76D8\u6839\u76EE\u5F55\u4E0B\u7684log.log\u6587\u4EF6\u4E2D
log4j.appender.RollingFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RollingFile.File=F:\\u5174\u55101903\JDBC
log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.RollingFile.layout.ConversionPattern=%d [%t] %-5p %-40.40c %X{traceId}-%m%n

你可能感兴趣的:(Java项目,JAVA学习)