目录
需求:springboot项目部署到服务器,采用的是外置配置文件.properties,为了安全起见,项目启动时需要对配置文件中的明文密码进行加密,解密(项目启动需要对密文解密才能连接相应数据库)。
解决办法:
采用jasypt解决
1.引入依赖
<!--配置文件密码加密-->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.4</version>
</dependency>
引入插件
<!--加密明文信息-->
<plugin>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-maven-plugin</artifactId>
<version>3.0.4</version>
</plugin>
2.启动类添加注解
@EnableEncryptableProperties,启用加密属性。
3.加密代码
在项目启动完成之后,紧接着要先执行加密代码。
在SpringBoot中,提供了一个接口:ApplicationRunner。
该接口中,只有一个run方法,他执行的时机是:spring容器启动完成之后,就会紧接着执行这个接口实现类的run方法。
这里有几点说明:
这个实现类,要注入到spring容器中,这里使用了@Component注解;
在同一个项目中,可以定义多个ApplicationRunner的实现类,他们的执行顺序通过注解@Order注解或者再实现Ordered接口来实现。
run方法的参数:ApplicationArguments可以获取到当前项目执行的命令参数。(比如把这个项目打成jar执行的时候,带的参数可以通过ApplicationArguments获取到);
由于该方法是在容器启动完成之后,才执行的,所以,这里可以从spring容器中拿到其他已经注入的bean。
@Component
@Order(value = 1)
@Slf4j
public class EncryptProfile implements ApplicationRunner {
/*加密算法*/
private final String algorithm = "PBEWithMD5AndDES";
/*加密密钥(可自定义,加解密需相同)*/
private final String secretKey = "BPCSecretKey";
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("执行加密方法");
String filePath = "/app/home/bpc/bpc-core-conf.properties";
log.info("配置文件路径=========================="+filePath);
SafeProperties properties= new SafeProperties();
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(filePath);
properties.load(fileInputStream);
fileInputStream.close();
} catch (IOException e) {
log.info("+++++++++++++++========没有找到外置配置文件(开发环境请忽略)!!!!!!!!===========++++++++++++++++++++++=================================");
}
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
String key = entry.getKey().toString();
if ((key.contains(".password") || key.contains(".pwd") )&& key.length() > 9) {
String substringKey = key.substring(key.length() - 9);
//对所有密码进行加密
if (substringKey.contains(".password") || substringKey.contains(".pwd")) {
String value = properties.getProperty(key);
if (!value.contains("ENC")) {
//加密
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
EnvironmentPBEConfig config = new EnvironmentPBEConfig();
config.setAlgorithm(algorithm);
config.setPassword(secretKey);
standardPBEStringEncryptor.setConfig(config);
String encryptedText = standardPBEStringEncryptor.encrypt(value);
log.info("加密的属性key===" + key + "=========加密前====" + value + "=========加密后====" + encryptedText);
filePath = URLDecoder.decode(filePath, "utf-8");
properties.setProperty(key, "ENC(" + encryptedText + ")");
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
properties.store(fileOutputStream, "");
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (Exception e) {
log.error(String.valueOf(e));
}
}
}
}
}
}
}
工具类SafeProperties
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
@SuppressWarnings("all")
public class SafeProperties extends Properties {
private static final long serialVersionUID = 5011694856722313621L;
private static final String keyValueSeparators = "=: \t\r\n\f";
private static final String strictKeyValueSeparators = "=:";
private static final String specialSaveChars = "=: \t\r\n\f#!";
private static final String whiteSpaceChars = " \t\r\n\f";
private PropertiesContext context = new PropertiesContext();
public PropertiesContext getContext() {
return context;
}
/*
* Converts encoded \uxxxx to unicode chars and changes special saved
* chars to their original forms
*/
public synchronized void load(InputStream inStream) throws IOException {
BufferedReader in;
in = new BufferedReader(new InputStreamReader(inStream, "8859_1"));
while (true) {
// Get next line
String line = in.readLine();
// intract property/comment string
String intactLine = line;
if (line == null)
return;
if (line.length() > 0) {
// Find start of key
int len = line.length();
int keyStart;
for (keyStart = 0; keyStart < len; keyStart++)
if (whiteSpaceChars.indexOf(line.charAt(keyStart)) == -1)
break;
// Blank lines are ignored
if (keyStart == len)
continue;
// Continue lines that end in slashes if they are not comments
char firstChar = line.charAt(keyStart);
if ((firstChar != '#') && (firstChar != '!')) {
while (continueLine(line)) {
String nextLine = in.readLine();
intactLine = intactLine + "\n" + nextLine;
if (nextLine == null)
nextLine = "";
String loppedLine = line.substring(0, len - 1);
// Advance beyond whitespace on new line
int startIndex;
for (startIndex = 0; startIndex < nextLine.length(); startIndex++)
if (whiteSpaceChars.indexOf(nextLine.charAt(startIndex)) == -1)
break;
nextLine = nextLine.substring(startIndex, nextLine.length());
line = new String(loppedLine + nextLine);
len = line.length();
}
// Find separation between key and value
int separatorIndex;
for (separatorIndex = keyStart; separatorIndex < len; separatorIndex++) {
char currentChar = line.charAt(separatorIndex);
if (currentChar == '\\')
separatorIndex++;
else if (keyValueSeparators.indexOf(currentChar) != -1)
break;
}
// Skip over whitespace after key if any
int valueIndex;
for (valueIndex = separatorIndex; valueIndex < len; valueIndex++)
if (whiteSpaceChars.indexOf(line.charAt(valueIndex)) == -1)
break;
// Skip over one non whitespace key value separators if any
if (valueIndex < len)
if (strictKeyValueSeparators.indexOf(line.charAt(valueIndex)) != -1)
valueIndex++;
// Skip over white space after other separators if any
while (valueIndex < len) {
if (whiteSpaceChars.indexOf(line.charAt(valueIndex)) == -1)
break;
valueIndex++;
}
String key = line.substring(keyStart, separatorIndex);
String value = (separatorIndex < len) ? line.substring(valueIndex, len) : "";
// Convert then store key and value
key = loadConvert(key);
value = loadConvert(value);
// memorize the property also with the whold string
put(key, value, intactLine);
} else {
// memorize the comment string
context.addCommentLine(intactLine);
}
} else {
// memorize the string even the string is empty
context.addCommentLine(intactLine);
}
}
}
private String loadConvert(String theString) {
char aChar;
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len);
for (int x = 0; x < len;) {
aChar = theString.charAt(x++);
if (aChar == '\\') {
aChar = theString.charAt(x++);
if (aChar == 'u') {
// Read the xxxx
int value = 0;
for (int i = 0; i < 4; i++) {
aChar = theString.charAt(x++);
switch (aChar) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
throw new IllegalArgumentException("Malformed \\uxxxx encoding.");
}
}
outBuffer.append((char) value);
} else {
if (aChar == 't')
outBuffer.append('\t'); /* ibm@7211 */
else if (aChar == 'r')
outBuffer.append('\r'); /* ibm@7211 */
else if (aChar == 'n') {
/*
* ibm@8897 do not convert a \n to a line.separator
* because on some platforms line.separator is a String
* of "\r\n". When a Properties class is saved as a file
* (store()) and then restored (load()) the restored
* input MUST be the same as the output (so that
* Properties.equals() works).
*
*/
outBuffer.append('\n'); /* ibm@8897 ibm@7211 */
} else if (aChar == 'f')
outBuffer.append('\f'); /* ibm@7211 */
else
/* ibm@7211 */
outBuffer.append(aChar); /* ibm@7211 */
}
} else
outBuffer.append(aChar);
}
return outBuffer.toString();
}
public synchronized void store(OutputStream out, String header) throws IOException {
BufferedWriter awriter;
awriter = new BufferedWriter(new OutputStreamWriter(out, "8859_1"));
if (header != null)
writeln(awriter, "#" + header);
List entrys = context.getCommentOrEntrys();
for (Iterator iter = entrys.iterator(); iter.hasNext();) {
Object obj = iter.next();
if (obj.toString() != null) {
writeln(awriter, obj.toString());
}
}
awriter.flush();
}
private static void writeln(BufferedWriter bw, String s) throws IOException {
bw.write(s);
bw.newLine();
}
private boolean continueLine(String line) {
int slashCount = 0;
int index = line.length() - 1;
while ((index >= 0) && (line.charAt(index--) == '\\'))
slashCount++;
return (slashCount % 2 == 1);
}
/*
* Converts unicodes to encoded \uxxxx and writes out any of the
* characters in specialSaveChars with a preceding slash
*/
private String saveConvert(String theString, boolean escapeSpace) {
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len * 2);
for (int x = 0; x < len; x++) {
char aChar = theString.charAt(x);
switch (aChar) {
case ' ':
if (x == 0 || escapeSpace)
outBuffer.append('\\');
outBuffer.append(' ');
break;
case '\\':
outBuffer.append('\\');
outBuffer.append('\\');
break;
case '\t':
outBuffer.append('\\');
outBuffer.append('t');
break;
case '\n':
outBuffer.append('\\');
outBuffer.append('n');
break;
case '\r':
outBuffer.append('\\');
outBuffer.append('r');
break;
case '\f':
outBuffer.append('\\');
outBuffer.append('f');
break;
default:
if ((aChar < 0x0020) || (aChar > 0x007e)) {
outBuffer.append('\\');
outBuffer.append('u');
outBuffer.append(toHex((aChar >> 12) & 0xF));
outBuffer.append(toHex((aChar >> 8) & 0xF));
outBuffer.append(toHex((aChar >> 4) & 0xF));
outBuffer.append(toHex(aChar & 0xF));
} else {
if (specialSaveChars.indexOf(aChar) != -1)
outBuffer.append('\\');
outBuffer.append(aChar);
}
}
}
return outBuffer.toString();
}
/**
* Convert a nibble to a hex character
*
* @param nibble
* the nibble to convert.
*/
private static char toHex(int nibble) {
return hexDigit[(nibble & 0xF)];
}
/** A table of hex digits */
private static final char[] hexDigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
'F' };
public synchronized Object put(Object key, Object value) {
context.putOrUpdate(key.toString(), value.toString());
return super.put(key, value);
}
public synchronized Object put(Object key, Object value, String line) {
context.putOrUpdate(key.toString(), value.toString(), line);
return super.put(key, value);
}
public synchronized Object remove(Object key) {
context.remove(key.toString());
return super.remove(key);
}
class PropertiesContext {
private List commentOrEntrys = new ArrayList();
public List getCommentOrEntrys() {
return commentOrEntrys;
}
public void addCommentLine(String line) {
commentOrEntrys.add(line);
}
public void putOrUpdate(PropertyEntry pe) {
remove(pe.getKey());
commentOrEntrys.add(pe);
}
public void putOrUpdate(String key, String value, String line) {
PropertyEntry pe = new PropertyEntry(key, value, line);
remove(key);
commentOrEntrys.add(pe);
}
public void putOrUpdate(String key, String value) {
PropertyEntry pe = new PropertyEntry(key, value);
int index = remove(key);
commentOrEntrys.add(index, pe);
}
public int remove(String key) {
for (int index = 0; index < commentOrEntrys.size(); index++) {
Object obj = commentOrEntrys.get(index);
if (obj instanceof PropertyEntry) {
if (obj != null) {
if (key.equals(((PropertyEntry) obj).getKey())) {
commentOrEntrys.remove(obj);
return index;
}
}
}
}
return commentOrEntrys.size();
}
class PropertyEntry {
private String key;
private String value;
private String line;
public String getLine() {
return line;
}
public void setLine(String line) {
this.line = line;
}
public PropertyEntry(String key, String value) {
this.key = key;
this.value = value;
}
/**
* @param key
* @param value
* @param line
*/
public PropertyEntry(String key, String value, String line) {
this(key, value);
this.line = line;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String toString() {
if (line != null) {
return line;
}
if (key != null && value != null) {
String k = saveConvert(key, true);
String v = saveConvert(value, false);
return k + "=" + v;
}
return null;
}
}
}
/**
* @param comment
*/
public void addComment(String comment) {
if (comment != null) {
context.addCommentLine("#" + comment);
}
}
}
4.解密代码
@Slf4j
public class DecryptConfigurationFile implements EncryptablePropertyResolver {
/*加密算法*/
private final String algorithm = "PBEWithMD5AndDES";
/*加密密钥(可自定义,加解密需相同)*/
private final String secretKey = "BPCSecretKey";
//解密方法
@Override
public String resolvePropertyValue(String s) {
if (null != s && s.contains("ENC")) {
String value = s.substring(3);
//解密
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
EnvironmentPBEConfig config = new EnvironmentPBEConfig();
config.setAlgorithm(algorithm);
config.setPassword(secretKey);
standardPBEStringEncryptor.setConfig(config);
String encryptedText = standardPBEStringEncryptor.decrypt(value);
return encryptedText;
}
return s;
}
5.注入解密bean
启动时要进行解密操作,所以我们在启动类里注入解密的bean
@SpringBootApplication
@EnableEncryptableProperties
public class DemoApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(DemoApplication .class, args);
}
/**
* 解密配置文件密文
*
* @returne
*/
@Bean
public EncryptablePropertyResolver encryptablePropertyResolver() {
return new DecryptConfigurationFile();
}
}