SpringBoot项目中对数据库连接进行加密

加密的目的在于安全性,否则有心人反编译你的项目后,拿到你的配置文件,你没有加密,获取到你数据库的账号密码.

一:druid方式实现对数据库密码进行加密

缺点:只能对数据库的用户名和密码或者url中的一个实现加密,不能同时实现三者的加密,安全级别比较低。

第一步:引入druid依赖

加入druid

     <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.8</version>
        </dependency>

完整依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--        MyBatis启动器-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
<!--        Mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>2.6.4</version>
        </dependency>
        <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.8</version>
        </dependency>
    </dependencies>

第二步:DruidUtils工具类–生成公钥和密码密文

com.alibaba.druid.filter.config.ConfigTools;
生成密文和公钥

package com.lz.jiaotong.utils;

import com.alibaba.druid.filter.config.ConfigTools;


public class DruidUtils {
    /**
     * 该方法实现对数据库用户名的加密
     * @param s
     * @return
     * @throws Exception
     */
    public static String username(String s) throws Exception {
        
        System.out.println("明文密码: " + s);
        String[] keyPair = ConfigTools.genKeyPair(512);
        //私钥
        String privateKey = keyPair[0];
        //公钥
        String publicKey = keyPair[1];
        //用私钥加密后的密文
        s = ConfigTools.encrypt(privateKey, s);

        System.out.println("privateKey:" + privateKey);
        System.out.println("publicKey:" + publicKey);

        System.out.println("password:" + s);

        String decryptPassword = ConfigTools.decrypt(publicKey, s);
        return decryptPassword;
    }

    /**
     * 改方法实现对数据库密码的加密
     * @param s
     * @return
     * @throws Exception
     */
    public static String password(String s) throws Exception {

        System.out.println("明文密码: " + s);
        String[] keyPair = ConfigTools.genKeyPair(512);
        //私钥
        String privateKey = keyPair[0];
        //公钥
        String publicKey = keyPair[1];
        //用私钥加密后的密文
        s = ConfigTools.encrypt(privateKey, s);

        System.out.println("privateKey:" + privateKey);
        System.out.println("publicKey:" + publicKey);

        System.out.println("s:" + s);

        String decryptPassword = ConfigTools.decrypt(publicKey, s);
        return decryptPassword;
    }
}

第三步:application.properties修改配置文件

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/javaweb?useSSL=false
spring.datasource.username=root
spring.datasource.password=Q1FNld+NHibXOAun74OXAYBiveAr+xIqW0A2OPnCJSJAjLyMUjMyu2QaBhNzQgTuR0p1qYUjJv2TwSrSsPI4hA==
spring.datasource.druid.filter.config.enabled=true
spring.datasource.druid.connect-properties.config.decrypt=true
spring.datasource.druid.connect-properties.config.decrypt.key=MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALChhVBs1YaTPnjBVBdrP48Lx4j5d4H3MW2a92x0m4ASd5xygZUZ0DtymVj+/OE1HONGnJPPlsjvG9ekV91xUXMCAwEAAQ==

第四步:验证

表结构

CREATE TABLE `td_user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `userName` varchar(64) DEFAULT NULL,
  `address` varchar(256) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

实体类

package com.lz.jiaotong.entity;

import java.io.Serializable;

public class User implements Serializable {
    private static final long serialVersionUID=1L;
    private Integer id;

    private String userName;
    private String address;

    public User(){}
    public User(Integer id, String userName, String address) {
        this.id = id;
        this.userName = userName;
        this.address = address;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
    public String getUserName() {
        return userName;}
    public void setUserName(String userName) {
        this.userName = userName;}
    public String getAddress() {
        return address;}
    public void setAddress(String address) {
        this.address = address;}
    public Integer getId() {
        return id;}
    public void setId(Integer id) {
        this.id = id;}
}

UserMapper接口

package com.lz.jiaotong.mapper;

import com.lz.jiaotong.entity.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface UserMapper {
    //查询所有用户
    @Select("select * from td_user")
    List<User> getAllUsers();
    //删除用户
    @Delete("delete from td_user where id=#{id}")
    void delete(Integer id);

}

USerService

package com.lz.jiaotong.service;
import com.lz.jiaotong.entity.User;
import java.util.List;
public interface UserService {
    //查询所有
    List<User> getAllUsers();
    //删除数据
    void deleteUser(Integer id);
}

UserServiceImpl实现类

package com.lz.jiaotong.service.impl;

import com.lz.jiaotong.mapper.UserMapper;
import com.lz.jiaotong.service.UserService;
import com.lz.jiaotong.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    //注入用户Mapper
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> getAllUsers() {
        return this.userMapper.getAllUsers();
    }
      //删除用户
    @Override
    public void deleteUser(Integer id) {
        System.out.println("删除了id为:"+id+"的用户");
        this.userMapper.delete(id);
    }
}

UserController控制类

package com.lz.jiaotong.controller;
import com.lz.jiaotong.entity.User;
import com.lz.jiaotong.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/list")
    @ResponseBody
    public List<User> list(){
        return  userService.getAllUsers();
    }
}

结果显示
在这里插入图片描述

二:jasypt方式加密

优点:在druid方式基础上,可以加入url和用户名、密码的同时加密

第一步:引入jasypt 依赖

      <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>

第二步:工具类

package com.lz.jiaotong.utils;

import org.jasypt.util.text.BasicTextEncryptor;
public class EncryptUtil {
    public static void urlAndUsernameAndPassword(String url,String username,String password) {
        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        // 加密秘钥(盐)
        textEncryptor.setPassword("!qaz@wsx#edc");
        // 要加密的数据(数据库的用户名或密码)
        String username1 = textEncryptor.encrypt(username);
        String password1 = textEncryptor.encrypt(password);
        String url1= textEncryptor.encrypt(url);
        System.out.println("url"+url1);
        System.out.println("username:" + username1);
        System.out.println("password:" + password1);
    }

    public static void main(String[] args) {
         //生成密文
        EncryptUtil.urlAndUsernameAndPassword("jdbc:mysql://localhost:3306/javaweb?useSSL=false","root","123456");
    }
}

第三步:application.properties修改配置文件

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#密码秘钥(盐)
jasypt.encryptor.password=!qaz@wsx#edc

spring.datasource.url=ENC(bSmU68s6kwxN8eEayf71HFksMAuyfyFTygzq8rFOn+TQtCdQInQ8MmwyTqmygJ1s9wPi2pWrlA82hCCPTbJ1/w==)

spring.datasource.username=ENC(q/mkp1F7tHwHhgnnhPqGZw==)
spring.datasource.password=ENC(DfdOr/8+jkK/4uhR2JLbjw==)

第四步:测试验证

在这里插入图片描述

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐