客戶端(CS)應用嵌入MyBatis時,數據庫連接配置(用戶名/密碼/URL)不可明文存放。本文實戰演示:MyBatis XML配置雙向加密存儲為.data二進制文件、運行時解密輸入流構建SqlSessionFactory、單例模式管理、類加載器路徑解析,適用於Swing/JavaFX/昇級包等桌面應用。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="app_user"/>
<property name="password" value="plain_password"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/isea/dao/UserMapper.xml"/>
</mappers>
</configuration>
public class MyBatis {
private static final String CONFIG = "basic.data"; // 加密文件名
private static MyBatis instance = new MyBatis();
private SqlSessionFactory sqlSessionFactory;
private MyBatis() {
try (InputStream is = getDecryptedConfigStream()) {
if (is == null) throw new RuntimeException("數據庫配置解密失敗");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
throw new RuntimeException("MyBatis初始化失敗", e);
}
}
// 解密配置文件返回 InputStream
private InputStream getDecryptedConfigStream() {
try {
// 1. 定位文件 (類加載器路徑)
String basePath = Config.getRealPath(); // 見下文
File encFile = new File(basePath, CONFIG);
// 2. 讀取加密內容
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(encFile))) {
String line;
while ((line = br.readLine()) != null) sb.append(line);
}
// 3. DES 解密
EncrypDES des = new EncrypDES();
String xmlContent = des.Decryptor(sb.toString());
// 4. 轉為 InputStream
return new ByteArrayInputStream(xmlContent.getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
log.error("配置解密失敗", e);
return null;
}
}
public static MyBatis getInstance() { return instance; }
public SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; }
}
public class Config {
public static String LOCATION;
static {
try { LOCATION = getRealPath(); }
catch (Exception e) { throw new RuntimeException(e); }
}
public static String getRealPath() throws Exception {
// 獲取類加載器根路徑 (classes目錄或jar包位置)
String path = Config.class.getClassLoader().getResource("").getFile();
File file = new File(path);
path = file.getAbsolutePath();
// 處理URL編碼空格等特殊字符
return java.net.URLDecoder.decode(path, "UTF-8");
}
}
public class EncrypDES {
private static final String KEY = "MyBatisKey"; // 8字節密鑰
private static final AlgorithmParameterSpec IV = new IvParameterSpec(KEY.getBytes());
private static final SecretKeySpec KEY_SPEC = new SecretKeySpec(KEY.getBytes(), "DES");
public String Decryptor(String encrypted) throws Exception {
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, KEY_SPEC, IV);
byte[] decoded = Base64.getDecoder().decode(encrypted);
return new String(cipher.doFinal(decoded), "UTF-8");
}
public String Encryptor(String plain) throws Exception {
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, KEY_SPEC, IV);
byte[] encrypted = cipher.doFinal(plain.getBytes("UTF-8"));
return Base64.getEncoder().encodeToString(encrypted);
}
}
// 開發期運行一次,生成 basic.data 放入 src/main/resources
public class EncryptConfig {
public static void main(String[] args) throws Exception {
String xml = FileUtils.readFileToString(new File("src/main/resources/mybatis-config.xml"), "UTF-8");
String encrypted = new EncrypDES().Encryptor(xml);
FileUtils.writeStringToFile(new File("src/main/resources/basic.data"), encrypted, "UTF-8");
}
}
AES-256-GCM或ChaCha20-Poly1305HMAC-SHA256防篡改EncrypDES類,增加逆向難度DataSourceFactory+Configuration代碼構建,僅加密敏感屬性DataSource dataSource = new PooledDataSource(driver, url, user, encryptedPassword);
TransactionFactory txFactory = new JdbcTransactionFactory();
Environment env = new Environment("dev", txFactory, dataSource);
Configuration config = new Configuration(env);
config.addMapper(UserMapper.class); // 直接註冊Mapper接口
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(config);