Mybatis-Plus数据安全保护-及其使用方法
①、防止删库跑路
得到十六位随机密钥(由核心人员保存)
@Test
void test(){ //生成十六位随机AES密钥
String randomKey= AES.generateRandomKey();
System.out.println(randomKey);
}
并用生成的十六位随机密码对需要加密的数据进行加密,如数据库url,username,password
@Test
void test01() {
//生成的十六位随机AES密钥
String randomKey = "bd8526e2b6b6ace8";
//使用随机密钥加密需要加密的数据,列如数据库url,username,password
String url = "jdbc:mysql://localhost:3306/mybatisplus?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8";
String username = "root";
String password = "admin";
String aesUrl = AES.encrypt(url, randomKey);
String aesUsername = AES.encrypt(username, randomKey);
String aesPassword = AES.encrypt(password, randomKey);
System.out.println("url:"+aesUrl);
System.out.println("username:"+aesUsername);
System.out.println("password:"+aesPassword);
}
# 生产环境
# 数据源
spring:
datasource:
#username: root
#password: admin
# 加密数据
username: mpw:vSwP+pBG9qRixd7SwbqFuA==
password: mpw:QJiZjLAeDB/ed3ebNX46Kg==
#url: jdbc:mysql://localhost:3306/mybatisplus?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
#driver-class-name: com.mysql.cj.jdbc.Driver
# 数据库安全
url: mpw:UXllUrEVHvn8iFpm0L/LMyUvQ+E81nwubz0ISIL6T0LrbrC+tEBUa3euZyH1Df/npcCoDtgYOBbtn/AbgpDrRck2DjLSVNHm9y7V2Z67TSmnRkIW2T6Kq28+qC3CASl1RlIT35kZXp22E++UxxIVpA==
driver-class-name: com.p6spy.engine.spy.P6SpyDriver
type: com.alibaba.druid.pool.DruidDataSource
注意!
- 加密配置必须以 mpw: 字符串开头
- 随机密钥请负责人妥善保管,当然越少人知道越好。
- 本地是不能连接数据库的,这个是用于生产环境的
使用方法:
1.在启动类种随便实现一个查询,能查询到证明数据库访问成功
启动类:
@SpringBootApplication
@MapperScan("com.tulingxueyuan.mp.mapper")
public class Application {
static EmployeeService employeeService;
@Autowired
public void setEmployeeService(EmployeeService employeeService) {
Application.employeeService = employeeService;
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
//此处若能查找到数据表示成功解密(证明加密生效)
System.out.println(employeeService.getById(1));
}
}
2.打包刚才项目为jar包,并利用命令行启动
1)、打包
2)、去到jar包所在目录,在当前目录下执行cmd命令
3)在cmd中,输入命令:java -jar 04_expand_test-0.0.1-SNAPSHOT.jar --mpw.key=bd8526e2b6b6ace8 --spring.profiles.active=prod
出现查询语句,证明解密成功!也就是在生产环境种使用成功