最近项目里要求把配置文件的信息做一下打包加密,运行时解密,具体实现如下
由于之前项目配置用了autoconfig,我这边改不了插件的源码,于是自己新建了一个插件
名字就叫encrypt吧
pom信息:
实现AbstractMojo:只做了一件事,就是把配置文件的value读出来做base64,具体的加密算法可以根据要求替换掉
packagecom.urfresh.maven.plugin;
importcom.urfresh.common.utils.encrypt.Base64Util;
importorg.apache.maven.plugin.AbstractMojo;
importorg.apache.maven.plugin.MojoExecutionException;
importjava.io.*;
importjava.util.Properties;
/**
* Goal which targetes a timestamp file.
*
* @goal encrypt
* @phase process-sources
*/
public classEncryptMojoextendsAbstractMojo {
/**
* @parameter
*/
privateFilesourceProperties;
/**
* @parameter
*/
privateStringtargetFileName;
private static finalStringLOG="log";
public voidexecute()throwsMojoExecutionException {
File source =sourceProperties;
if(!source.exists()) {
throw newIllegalArgumentException("no source found ! ");
}
File target =newFile(source.getParentFile(),targetFileName);
if(target.exists()) {
booleane = target.delete();
if(!e) {
throw newIllegalStateException("delete old fail ! ");
}
}
try{
booleans = target.createNewFile();
if(!s) {
throw newIllegalStateException("create target fail ! ");
}
}catch(IOException e) {
e.printStackTrace();
throw newMojoExecutionException("ioException",e);
}
FileWriter w =null;
Properties properties =null;
try{
w =newFileWriter(target);
properties =newProperties();
properties.load(newFileReader(source));
if(properties.isEmpty()){
return;
}
for(String name : properties.stringPropertyNames()){
String value = properties.getProperty(name);
if(!value.contains(LOG)){
value = doEncrypt(value);
}
StringBuilder sb =newStringBuilder(name);
sb.append("=").append(value);
w.write(sb.toString());
w.write('\n');
w.flush();
}
}catch(IOException e) {
throw newMojoExecutionException("Error creating file "+ target,e);
}finally{
if(w !=null) {
try{
w.close();
}catch(IOException e) {
// ignore
}
}
}
}
privateStringdoEncrypt(String s) {
returnBase64Util.encodeToString(s.getBytes());
}
}
将这个插件引入项目,并更改之前autoconfig的文件为加密后的文件
覆盖spring解析的默认实现并在xml中替换掉
到这里就可以打包发布啦
具体的加密与解密算法暂时还没有实现,后面再看吧!嘿嘿