版權(quán)聲明: https://blog.csdn.net/Dongguabai/article/details/81114569
主要參考博客:https://blog.csdn.net/sz85850597/article/details/80396321
主要使用的jasypt-spring-boot這個(gè)開源工具,。
引入maven依賴
配置加解密Bean
public class EncryptionPropertyConfig { @Bean(name = "encryptablePropertyResolver") public EncryptablePropertyResolver encryptablePropertyResolver() { return new EncryptionPropertyResolver(); class EncryptionPropertyResolver implements EncryptablePropertyResolver { public String resolvePropertyValue(String value) { if (StringUtils.isBlank(value)) { if (value.startsWith("DES@")) { return resolveDESValue(value.substring(4)); private String resolveDESValue(String value) { return DesUtil.decrypt(value, DesUtil.KEY);
編寫加解密工具類
之前在github上找到的工具類,,抱歉之前沒留下原地址,。
@NoArgsConstructor(access = AccessLevel.PRIVATE) public final static String KEY = "ScAKC0XhadTHT3Al0QIDAQAB"; public static String encrypt(String data,String key) { String encryptedData = null; // DES算法要求有一個(gè)可信任的隨機(jī)數(shù)源 SecureRandom sr = new SecureRandom(); DESKeySpec deskey = new DESKeySpec(key.getBytes()); // 創(chuàng)建一個(gè)密匙工廠,,然后用它把DESKeySpec轉(zhuǎn)換成一個(gè)SecretKey對象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(deskey); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr); // 加密,,并把字節(jié)數(shù)組編碼成字符串 encryptedData = new sun.misc.BASE64Encoder().encode(cipher.doFinal(data.getBytes())); throw new RuntimeException("加密錯(cuò)誤,,錯(cuò)誤信息:", e); public static String decrypt(String cryptData,String key) { String decryptedData = null; // DES算法要求有一個(gè)可信任的隨機(jī)數(shù)源 SecureRandom sr = new SecureRandom(); DESKeySpec deskey = new DESKeySpec(key.getBytes()); // 創(chuàng)建一個(gè)密匙工廠,,然后用它把DESKeySpec轉(zhuǎn)換成一個(gè)SecretKey對象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(deskey); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, secretKey, sr); // 把字符串解碼為字節(jié)數(shù)組,并解密 decryptedData = new String(cipher.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(cryptData))); throw new RuntimeException("解密錯(cuò)誤,,錯(cuò)誤信息:", e); public static void main(String[] args) { System.out.println("url::"+encrypt("jdbc:oracle:thin:@127.0.0.1:1521:xe",KEY)); System.out.println("username::"+encrypt("admin",KEY)); System.out.println("password::"+encrypt("admin",KEY));
工具類中的main方法執(zhí)行結(jié)果為:
修改properties文件
運(yùn)行項(xiàng)目測試通過!
|