什么是MD5加密?
一种加密手段。
为什么使用MD5进行加密?
为了防止信息泄露,造成不必要损失。
怎样做MD5加密?
注册登录简单实战(数据库)
项目结构
Main.java
package com.jd.test;
import java.util.Scanner;
import java.util.UUID;
import com.jd.tool.db.DBLink;
import com.jd.tool.db.MD5Tool;
public class Main {
public static void main(String[] args) {
System.out.println("*********************************");
System.out.println("*\t\t\t\t*");
System.out.println("*\t欢迎使用注册登录系统\t\t*");
System.out.println("*\t\t\t\t*");
System.out.println("*********************************");
while (true) {
menu();
}
}
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("欢迎使用注册系统");
System.out.println("请输入用户名");
String user_name = scanner.next();
String sql = "select id from user_info where user_name=?";
if(new DBLink().exist(sql,user_name)) {
System.out.println("用户名已存在,请重新输入");
break;
}
System.out.println("请输入密码");
String password = scanner.next();
System.out.println("请确认密码");
String repassword = scanner.next();
if(password.equals(repassword)) {
password = MD5Tool.encrypt(password);
String id = UUID.randomUUID().toString();
sql = "insert into user_info(id,user_name,password) values ('"+id+"',?,?)";
if(new DBLink().update(sql,user_name,password)) {
System.out.println("注册成功");
break;
}
}
System.out.println("两次密码不一致,注册失败");
break;
}
case 2:{
System.out.println("欢迎使用登录系统");
System.out.println("请输入用户名");
String user_name = 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, user_name,password)) {
System.out.println("登录成功");
break;
}
System.out.println("用户名或密码错误,登录失败");
break;
}
case 3:{
System.out.println("已退出系统");
System.exit(0);
break;
}
default:
System.out.println("I'm Sorry,there is not the "+option+" option,please try again.");
}
}
}
tool
DBLink.java
package com.jd.tool.db;
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;
import com.jd.tool.PropertiesTool;
/**
* 数据库管理工具类
*
* @author Administrator
*/
public class DBLink {
private Logger logger = Logger.getLogger(DBLink.class);
/**
* 获取数据库连接
*
* @author Administrator
*/
private Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");//加载驱动
String userName = PropertiesTool.getvalue("db.username");
String password = PropertiesTool.getvalue("db.password");
String url = PropertiesTool.getvalue("db.url");
return DriverManager.getConnection(url, userName, password);//创建连接
} catch (Exception e) {
logger.debug(e.getMessage(), e);
}
return null;
}
/**
* 查询数据
*
* @author Administrator
*/
public void select(String sql,IRowMapper rowMapper,Object...params) {//接口无法创建对象,所以rowMapper参数一定指向IRowMapper接口实现类对象
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();//executeQuery()方法会把数据库响应的查询结果存放在ResultSet类对象中供我们使用
rowMapper.IRowMapper(resultSet);//因为rowMapper参数指向IRowMapper接口实现类对象,所以此处将调用接口实现类中所实现的rowMapper方法 多态
} catch (Exception e) {
logger.debug(e.getMessage(), e);
}finally {
close(resultSet,preparedStatement,connection);
}
}
/**
* 修改(insert,update和delete)数据
*
* @author Administrator
*/
public boolean update(String sql) {
Connection connection = null;//提升作用域
Statement statement = null;
try {
connection = getConnection();
statement = connection.createStatement();
int result = statement.executeUpdate(sql);//执行SQL语句,返回受影响的语句行数
//statement.close();//如果前面代码出错,下面代码将会不执行,所以不能写在这里
//connection.close();
return result>0;
} catch (Exception e) {
logger.debug(e.getMessage(), e);
}finally {
close(statement,connection);
}
return false;
}
/**
* 修改(insert,update和delete)数据
*
* @author Administrator
*/
public boolean update(String sql,Object...params) {
Connection connection = 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]);
}
return preparedstatement.executeUpdate()>0;
} catch (Exception e) {
logger.debug(e.getMessage(), e);
}finally {
close(preparedstatement,connection);
}
return false;
}
/**
* 判断SQL语句是否能查出数据
*
* @author Administrator
*/
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, params[i]);//为占位符传值
}
resultSet = preparedStatement.executeQuery();
return resultSet.next();//判断是否有值
} catch (Exception e) {
logger.debug(e.getMessage(), e);
}finally {
close(resultSet,preparedStatement,connection);
}
return false;
}
/**
* 释放资源
*
* @author Administrator
*/
private void close(Statement statement,Connection connection) {
try {
if(statement!=null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(connection!=null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 释放资源
*
* @author Administrator
*/
private void close(ResultSet resultSet,Statement statement,Connection connection) {//方法的重载
try {
if(resultSet!=null) {
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
close(statement,connection);
}
}
IRowMapper.java
package com.jd.tool.db;
import java.sql.ResultSet;
public interface IRowMapper {
void IRowMapper(ResultSet rs);
}
MD5Tool.java
package com.jd.tool.db;
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;
}
}
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://localhost: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=D://log.log
log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.RollingFile.layout.ConversionPattern=%d [%t] %-5p %-40.40c %X{traceId}-%m%n
说明:
项目中使用了两次MD5加密,
第一次,注册时,密码与确认密码一致,进行加密,将密码通过MD5变为32位的字符串,传到数据库中。
第二次,登录时,将输入的密码进行加密,转换为32位的字符串,若与数据库中的32位字符串相同,即登录成功。
MD5加密保证了数据的安全性,但也不绝对安全,目前已知的MD5解码就已经达到95%的正确率了。(手动狗头)