springboot连接数据库实现md5+salt加密demo(用户登录注册详细源码)

springboot连接数据库实现md5加密

运用场景:
作为常用的数据库加密方式,把用户的密码进行加密后保存到数据库,不将用户密码暴露给数据库管理员,从而保证安全。但是一些网站支持md5解码,所以我们可以人为地增加解码难度,给密码加盐操作,保证我们的密码不那么容易被破解。
原理:
用户注册时,将个人的密码进行md5+salt加密后保存到数据库中,登录输入账号密码时,前端form表单将用户输入的密码传回后端,后端将接收到的密码同样进行加密后,和数据库的加密密码进行验证,比对成功后登录成功。

项目结构:

springboot连接数据库实现md5+salt加密demo(用户登录注册详细源码)_第1张图片

实现:

1、创建一个springboot项目

底层搭建:

2、需要的依赖,pom.xml:


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.7.3version>
        <relativePath/> 
    parent>
    <groupId>com.mestgroupId>
    <artifactId>md5artifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>md5name>
    <description>Demo project for Spring Bootdescription>
    <properties>
        <java.version>1.8java.version>
    properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>com.microsoft.sqlservergroupId>
            <artifactId>mssql-jdbcartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>commons-codecgroupId>
            <artifactId>commons-codecartifactId>
            <version>1.6version>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-annotationartifactId>
            <version>3.5.1version>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-coreartifactId>
            <version>3.5.1version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.7version>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>1.1.1version>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombokgroupId>
                            <artifactId>lombokartifactId>
                        exclude>
                    excludes>
                configuration>
            plugin>
        plugins>
    build>

project>

3、配置数据库和thymeleaf
application.properties:

spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.thymeleaf.prefix=classpath:templates/

md5_user表:
springboot连接数据库实现md5+salt加密demo(用户登录注册详细源码)_第2张图片

前端页面

4、前端html
login.html:

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录title>
    
    <script src="https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.min.js">script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        html {
            height: 100%;
        }

        body {
            height: 100%;
        }

        .container {
            height: 100%;
            background-image: linear-gradient(to right, #fbc2eb, #a6c1ee);
        }

        .login-wrapper {
            background-color: #fff;
            width: 358px;
            height: 588px;
            border-radius: 15px;
            padding: 0 50px;
            position: relative;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }

        .header {
            font-size: 38px;
            font-weight: bold;
            text-align: center;
            line-height: 200px;
        }

        .input-item {
            display: block;
            width: 100%;
            margin-bottom: 20px;
            border: 0;
            padding: 10px;
            border-bottom: 1px solid rgb(128, 125, 125);
            font-size: 15px;
            outline: none;
        }

        .input-item:placeholder {
            text-transform: uppercase;
        }

        .btn {
            text-align: center;
            padding: 10px;
            width: 45%;
            margin-top: 40px;
            background-image: linear-gradient(to right, #a6c1ee, #fbc2eb);
            color: #fff;
        }

        a {
            text-decoration-line: none;
            color: #abc1ee;
        }
    style>
head>
<body>
<div class="container">
    <div class="login-wrapper">
        <div class="header">Logindiv>

        <p style="color: #ff0000" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}">p>

        <form th:action="@{/login}" method="post">
            <div class="form-wrapper">
                <input type="text" id="username" name="username" placeholder="username" class="input-item">
                <input type="password" id="password" name="password" placeholder="password" class="input-item">

                <div>
                    <input type="submit" value="Login" class="btn" onclick="pass()" style="margin-right: 30px">
                    <button class="btn" onclick="window.location.href='/register.html'" type="button" id="register">registerbutton>
                div>
            div>
        form>
    div>
div>
<script>
    function pass() {
        let uname=document.getElementById('username')
        let pwd = document.getElementById('password') // 获取 password 的属性值
        // let md5pwd = document.getElementById('md5_password') // 获取 md5_password 的属性值

        console.log(uname.value)
        console.log(pwd.value)
        // console.log(md5pwd)

        // MD5加密
        pwd.value = md5(pwd.value)
        console.log(pwd.value)
    }
script>
body>
html>

register.html:

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>注册title>
    <script src="https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.min.js">script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        html {
            height: 100%;
        }

        body {
            height: 100%;
        }

        .container {
            height: 100%;
            background-image: linear-gradient(to right, #fbc2eb, #a6c1ee);
        }

        .login-wrapper {
            background-color: #fff;
            width: 358px;
            height: 588px;
            border-radius: 15px;
            padding: 0 50px;
            position: relative;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }

        .header {
            font-size: 38px;
            font-weight: bold;
            text-align: center;
            line-height: 200px;
        }

        .input-item {
            display: block;
            width: 100%;
            margin-bottom: 20px;
            border: 0;
            padding: 10px;
            border-bottom: 1px solid rgb(128, 125, 125);
            font-size: 15px;
            outline: none;
        }

        .input-item:placeholder {
            text-transform: uppercase;
        }

        .btn {
            text-align: center;
            padding: 10px;
            width: 26%;
            margin-top: 40px;
            background-image: linear-gradient(to right, #a6c1ee, #fbc2eb);
            color: #fff;
        }

        a {
            text-decoration-line: none;
            color: #abc1ee;
        }
         .error{
             color: red;
         }
    style>
head>
<body>
<div class="container">
    <div class="login-wrapper">
        <div class="header">请注册div>

        <form onsubmit="return validateForm()" th:action="@{/register}" method="post">
            <div class="form-wrapper">
                <input type="text" id="username" name="username" placeholder="账户:" class="input-item">
                <span class="error" id="nameErr">span>

                <input type="password" id="password" name="password" placeholder="密码:" class="input-item">
                <span class="error" id="pwdErr">span>

                <input type="password" id="repassword" name="repassword" placeholder="确认密码:" class="input-item">
                <span class="error" id="repwdErr">span>

                <div>
                    <button class="btn" type="submit" id="register" style="margin-right: 30px" onclick="beMd5()">注册button>
                    <button class="btn"  type="reset" style="margin-right: 30px">重置button>
                    <button class="btn"  type="button" onclick="window.location.href='/login.html'">返回button>
                div>
            div>
        form>
    div>
div>
<script>
    // 显示错误消息
    function printError(elemId, hintMsg) {
        document.getElementById(elemId).innerHTML = hintMsg;
    }
    // 验证表单数据
    function validateForm() {
        // 获取表单元素的值
        var username = document.querySelector("input[name='username']").value;
        var repassword = document.querySelector("input[name='repassword']").value;
        var password = document.querySelector("input[name='password']").value;


        if(username == "" || username == null){
            printError("nameErr", "用户名不能为空");
            return false;
        }
        if(password == "" || password == null){
            printError("pwdErr", "密码不能为空");
            return false;
        }
        if(repassword == "" || repassword == null){
            printError("repwdErr", "密码不能为空");
            return false;
        }
        if(password!=repassword){
            printError("repwdErr", "两次密码不一致");
            printError("pwdErr", "两次密码不一致");
            return false;
        }
    }
    function beMd5() {
        let uname=document.getElementById('username')
        let pwd = document.getElementById('password') // 获取 password 的属性值
        let repwd = document.getElementById('repassword') // 获取 password 的属性值

        console.log(uname.value)
        console.log(pwd.value)

        pwd.value = md5(pwd.value)
        repwd.value = md5(repwd.value)//这里对密码和确认密码都进行md5加密,因为会比对两次密码一致问题
        console.log(pwd.value)
    }

script>
body>
html>

success.html:

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>欢迎title>
head>
<body>
<h1>欢迎你h1>

body>
html>

后端:

5、MyMvcConfig.java视图解析器:

package com.mest.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Locale;

//如果你想自定义一些定制化的功能,只要写这个组件,然后将他交给springboot,springboot就会帮我们自动装配
//扩张springmvc dispatchservlet
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    //    ViewResolver 实现了视图解析器接口的类,我们就可以把他看作试图解析器
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("login");
        registry.addViewController("/login.html").setViewName("login");
        registry.addViewController("/success.html").setViewName("success");
        registry.addViewController("/register.html").setViewName("register");
    }

    public ViewResolver myViewResolver() {
        return new MyViewResolver();
    }

    public static class MyViewResolver implements ViewResolver {
        //自定义一个自己的试图解析器myViewResolver
        @Override
        public View resolveViewName(String viewName, Locale locale) throws Exception {
            return null;
        }
    }

}

6、MD5Controller:

package com.mest.controller;

import com.mest.mapper.UserMapper;
import com.mest.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
public class MD5Controller {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    public User user;

	//登录
    @RequestMapping("/login")
    public String Login(@RequestParam("username") String username,//接收从login.html 传参过来 参数:username
                        @RequestParam("password") String password,
                        Model model, //回显数据
                        HttpSession session) {


//        String md5Password = password;
        String md5Password = password + "mest";//后端加盐操作
        String finalPassword = DigestUtils.md5DigestAsHex(md5Password.getBytes());// 最终的 MD5 密码
        String uname = username;

        System.err.println("前端传的MD5密码:" + password);
        System.out.println("后端加密的MD5密码:" + finalPassword);


        if (userMapper.queryUser(uname, finalPassword) != null) {//如果查询结果不为空则用户、密码正确
            session.setAttribute("loginUser", username);//记录 session
            return "success";
        } else {
            model.addAttribute("msg", "用户名或者密码错误");
        }
        return "login";
    }
	//注册
    @RequestMapping("/register")
    public String register(@RequestParam("username") String username,
                           @RequestParam("password") String password) {

        String md5Password = password + "mest";//后端加盐操作
        String finalMD5Password = DigestUtils.md5DigestAsHex(md5Password.getBytes());// 前端传来的密码进行加密

        System.err.println("前端传的MD5密码:" + password);
        System.out.println("后端加密的MD5密码:" + finalMD5Password);

        if (username != null && password != null) {
            userMapper.addUser(username, finalMD5Password);//将加密后的密码插入数据库
        }
        return "login";
    }
}

7、UserMapper:
使用注解,未编写xml

package com.mest.mapper;

import com.mest.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

@Mapper
@Repository
public interface UserMapper {

    // 查询用户、密码是否存在
    @Select("select * from md5_user where username=#{username} and password=#{password}")
    User queryUser(@Param("username") String username, @Param("password") String password); //返回user结果

    // 添加用户、密码
    @Insert("insert into md5_user(username, password) values(#{username}, #{password}) ")
    int addUser(@Param("username") String username, @Param("password") String password);

}


8、User类:

package com.mest.pojo;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("md5_user")
@Component
public class User {
    private Integer id;
    private String username;
    private String password;
}

数据展示:

先注册:
admin 123
springboot连接数据库实现md5+salt加密demo(用户登录注册详细源码)_第3张图片查看提交的数据信息:

springboot连接数据库实现md5+salt加密demo(用户登录注册详细源码)_第4张图片把前端传来的数据加盐后存入数据库
此时数据库存入的数据就是md5再加盐和加密的数据:
数据库的数据:
springboot连接数据库实现md5+salt加密demo(用户登录注册详细源码)_第5张图片
登录

springboot连接数据库实现md5+salt加密demo(用户登录注册详细源码)_第6张图片输入账号密码:admin 123提交post请求,md5加密123后的密码:
202cb962ac59075b964b07152d234b70

springboot连接数据库实现md5+salt加密demo(用户登录注册详细源码)_第7张图片
springboot连接数据库实现md5+salt加密demo(用户登录注册详细源码)_第8张图片后端接收加密后的密码:202cb962ac59075b964b07152d234b70

再进行加盐操作:

String md5Password = password + “mest”;//后端加盐操作
String finalPassword = DigestUtils.md5DigestAsHex(md5Password.getBytes());// 最终的 MD5 密码

在这里插入图片描述

把最终的密码和数据库的密码进行比对

springboot连接数据库实现md5+salt加密demo(用户登录注册详细源码)_第9张图片
比对一致,登录
springboot连接数据库实现md5+salt加密demo(用户登录注册详细源码)_第10张图片

输入错误密码:
springboot连接数据库实现md5+salt加密demo(用户登录注册详细源码)_第11张图片总结:md5加密简单理解就是,输入的密码前端传回来,后端拿到进行加密加盐,用加密加盐后的密码和数据库比对。

你可能感兴趣的:(java后端开发,spring,boot,数据库,mybatis,安全)