1.依赖
<!--jasypt-->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
加密密钥
2_1直接写在yml(不安全)
jasypt:
encryptor:
password: ceshimiwen123123 #自己随便写
2_2作为启动参数
-Djasypt.encryptor.password=ceshimiwen123123
java -jar xxx.jar -Djasypt.encryptor.password=ceshimiwen123123
3.写个测试类(启动测试类时密钥直接放yml里就行,拿到加密后信息再放启动参数)
package ceshi.test;
import org.jasypt.encryption.StringEncryptor;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class JasyptTest {
/**
* 注入加密方法
*/
@Autowired
private StringEncryptor encryptor;
/**
* 手动生成密文,此处演示了url,user,password
*/
@Test
public void encrypt() {
String url = encryptor.encrypt("jdbc:mysql://localhost:3306/ceshi?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8");
String name = encryptor.encrypt("root");
String password = encryptor.encrypt("root");
System.out.println("database url: " + url);
System.out.println("database name: " + name);
System.out.println("database password: " + password);
Assert.assertTrue(url.length() > 0);
Assert.assertTrue(name.length() > 0);
Assert.assertTrue(password.length() > 0);
}
}
拿到加密后字符串
以ENC()包裹,例如:
启动成功
jasypt 默认使用 ENC() 包裹
修改前后缀
jasypt:
encryptor:
## 指定前缀、后缀
property:
prefix: 'PASS('
suffix: ')'
此时使用PASS() 包裹才会被解密
数据库内容加密
1.数据库函数
简单方法直接用函数加密:to_base64(字符串),解密:from_base64(字符串),有中文则使用去除乱码CONVERT(from_base64(字符串),CHAR)
2.springboot自带md5加密
import org.springframework.util.DigestUtils;
String md5Password = DigestUtils.md5DigestAsHex(字符串.getBytes());