背景:
原本項目中數據庫和中間件賬號密碼都是直接用明文配置的,畢竟這樣最方便開發,平時也沒人在乎這個。但是部署到實際項目中,甲方進行安全檢查第一個就查到這個,要求我們整改,那只能整了。
網上找了一些資料,好像大都用加密工具操作,官網看其他博客看了下,發現使用起來比較方便,直接簡單記錄下,
擴展:直接預研敏感數據加密技術,不只是對配置文件加密,對其他接口經過后臺的敏感數據也進行了解,包括數據加密、加密后的技術怎么進行模糊查詢等等,會在后續博客中進行編寫。當然這都是后話,下面直接操作進行配置文件賬號密碼加密。
實踐 1、引入依賴
com.github.ulisesbocchio
jasypt-spring-boot-starter
3.0.5
如果項目中啟動類沒有 @n或@ion注解本地配置密碼,那么需要引入--boot依賴且需要創建配置類并啟用 @和@本地配置密碼,進行聲明。
2、賬號密碼轉成加密值
創建一個工具類把我們的賬號密碼進行加密
import org.jasypt.properties.PropertyValueEncryptionUtils;
import org.jasypt.util.text.BasicTextEncryptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Jasypt加密工具類
* @author ppp
* @date 2023/1/5
*/
public class JasyptUtil {
private static final Logger logger = LoggerFactory.getLogger(JasyptUtil.class);
/**
* 加密使用密鑰,需要在和配置文件中的jasypt.encryptor.password保持一致
*/
private static final String PRIVATE_KEY = "demo";

/**
* BasicTextEncryptor對象初始化使用的算法就是"PBEWithMD5AndDES"
* 點擊進源碼構造方法中就可以看到下面的設置
* this.encryptor.setAlgorithm("PBEWithMD5AndDES");
*/
private static BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();
static {
basicTextEncryptor.setPassword(PRIVATE_KEY);
}
/**
* 明文加密
*
* @param plaintext 明文
* @return String

*/
public static String encrypt(String plaintext) {
logger.info("明文字符串為:{}", plaintext);
String ciphertext = basicTextEncryptor.encrypt(plaintext);
logger.info("密文字符串為:{}", ciphertext);
return ciphertext;
}
/**
* 解密
*
* @param ciphertext 密文
* @return String
*/
public static String decrypt(String ciphertext) {

logger.info("密文字符串為:{}", ciphertext);
ciphertext = "ENC(" + ciphertext + ")";
if (PropertyValueEncryptionUtils.isEncryptedValue(ciphertext)) {
String plaintext = PropertyValueEncryptionUtils.decrypt(ciphertext, basicTextEncryptor);
logger.info("明文字符串為:{}", plaintext);
return plaintext;
}
logger.error("解密失敗!");
return "";
}
public static void main(String[] args) {
String encrypt = encrypt("123456");
String test = decrypt(encrypt);
}

}
3、配置文件添加配置
.yml中添加配置
jasypt:
encryptor:
# 指定加密密鑰,生產環境請放到啟動參數里面 -Djasypt.encryptor.password=加密密鑰
password: demo
# 指定解密算法,需要和加密時使用的算法一致
algorithm: PBEWithMD5AndDES
# 指定initialization vector類型
iv-generator-classname: org.jasypt.iv.NoIvGenerator
4、替換賬號密碼
把.yml中需要加密的賬號密碼都換成 ENC(密文) 格式即可,啟用項目后他會檢測配置文件中ENC樣式的數據把里面的密文解密出來給框架使用。