添加依赖
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>1.18</version>
</dependency>
对数据进行加密
public class Jasypt {
public static void main(String[] args) {
//启动参数:-Djasypt.encryptor.password=eug83f3gG
String mySQLUsername = "root";
String mySQLPassword = "root";
String redisUsername = "";
String redisPassword = "123456";
BasicTextEncryptor encryptor = new BasicTextEncryptor();
//秘钥,启动程序时需要
encryptor.setPassword("eug83f3gG");
//密码进行加密
String newSQLUsername = encryptor.encrypt(mySQLUsername);
String newSQLPassword = encryptor.encrypt(mySQLPassword);
String newRedisUsername = encryptor.encrypt(redisUsername);
String newRedisPassword = encryptor.encrypt(redisPassword);
System.out.println("加密后账号:" + newSQLUsername);
System.out.println("加密后密码:" + newSQLPassword);
System.out.println("加密后Redis账户: " + newRedisUsername);
System.out.println("加密后Redis密码: " + newRedisPassword);
}
}
将加密的数据替换到配置文件中
ENC得加,程序启动时根据这个标识来进行解密的
datasource:
username: ENC(6mZZ8VoVkpe0v/sALiKiuw==)
password: ENC(Lbz2Kx6KpLghdyGTWoU8WQ==)
程序启动带上启动参数
idea中运行boot程序时可以在启动的哪里可以看到可以编辑配置,把下面的复制到环境中即可,如果是在服务器上使用Jar启动则命令加上下面这句话即可。
-Djasypt.encryptor.password=eug83f3gG
加密工具类编写
通过解析yaml文件对需要加密的数据进行加密,并将加密数据反写回配置文件中。
依赖引入
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
</dependency>
工具类编写
package com.gis.util;
import org.jasypt.util.text.BasicTextEncryptor;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.*;
import java.util.*;
/**
* @Author: 张定辉
* @CreateDate: 2022/10/12
* @Description: 加密工具类, 用于对配置文件中的敏感数据进行加密
*/
public class EncryptUtil {
private static final DumperOptions OPTIONS = new DumperOptions();
static {
//设置yaml读取方式为块读取
OPTIONS.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
OPTIONS.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
OPTIONS.setPrettyFlow(false);
}
private EncryptUtil() {
}
/**
* 对单个属性进行加密
*
* @param data 待加密数据
* @param privateKey 加密密钥
* @return 已加密数据
*/
public static String encrypt(String data, String privateKey) {
BasicTextEncryptor encryptor = new BasicTextEncryptor();
encryptor.setPassword(privateKey);
return encryptor.encrypt(data);
}
/**
* 对yaml配置文件进行加密,并将需要加密的数据反写回yaml文件中
*
* @param attributesFilePath yaml文件待加密属性配置文件路径,properties文件
* @param yamlPath 需要加密的yaml文件路径
* @param privateKey 加密密钥
*/
public static void encryptYaml(String attributesFilePath, String yamlPath, String privateKey) {
try
(FileInputStream yamlInput1 = new FileInputStream(yamlPath);
FileInputStream yamlInput2 = new FileInputStream(yamlPath);
BufferedReader reader = new BufferedReader(new FileReader(attributesFilePath))) {
List<String> attributesKeyList = new ArrayList<>();
String str;
//循环读取配置文件中需要加密的属性在yaml中的键
while ((str = reader.readLine()) != null) {
str = removeSpace(str);
attributesKeyList.add(str);
}
Yaml yaml = new Yaml(OPTIONS);
Map<?, ?> getValueMap = yaml.loadAs(yamlInput1, Map.class);
Map<String, Object> setValueMap = yaml.loadAs(yamlInput2, Map.class);
for (String s : attributesKeyList) {
String value = (String) getValue(s, getValueMap);
value = "ENC(" + encrypt(value, privateKey) + ")";
setValue(setValueMap, s, value);
}
yaml.dump(setValueMap, new FileWriter(yamlPath));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 去除空格
*
* @param str 待处理的字符
* @return 处理好的字符
*/
private static String removeSpace(String str) {
char[] ch = str.toCharArray();
StringBuilder builder = new StringBuilder();
for (char c : ch) {
if (c != ' ') {
builder.append(c);
}
}
return builder.toString();
}
/**
* 通过键获取yaml中的值
* @param key 取数键
* @param value yaml文件内容map
* @return 值
*/
private static Object getValue(String key, Map<?, ?> value) {
String delimiter = ".";
//递归终止条件,当键中不存在点时则返回
if (!key.contains(delimiter)) {
return value.get(key);
}
String currentKey = key.substring(0, key.indexOf('.'));
String nextKey = key.substring(key.indexOf('.') + 1);
if (value.get(currentKey) instanceof Map) {
LinkedHashMap<?, ?> nextValue = (LinkedHashMap<?, ?>) value.get(currentKey);
return getValue(nextKey, nextValue);
} else {
throw new NullPointerException("获取yaml中的值时错误,发生错误的键: " + key + ",请检查是否符合yaml文件编写规范");
}
}
public static void setValue(Map<String, Object> map, String key, Object value) {
String[] keys = key.split("\\.");
int len = keys.length;
Map<String, Object> temp = map;
for (int i = 0; i < len - 1; i++) {
if (temp.containsKey(keys[i])) {
temp = (Map<String, Object>) temp.get(keys[i]);
}
if (i == len - 2) {
temp.put(keys[i + 1], value);
}
}
for (int j = 0; j < len - 1; j++) {
if (j == len - 1) {
map.put(keys[j], temp);
}
}
}
public static void main(String[] args) {
encryptYaml("D:\\桌面\\tt1.ini", "D:\\桌面\\ttt.yaml", "GIS");
}
}