萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

MyBatis在CS客戶端應用:加密配置文件與SqlSessionFactory初始化實戰

客戶端(CS)應用嵌入MyBatis時,數據庫連接配置(用戶名/密碼/URL)不可明文存放。本文實戰演示:MyBatis XML配置雙向加密存儲為.data二進制文件、運行時解密輸入流構建SqlSessionFactory、單例模式管理、類加載器路徑解析,適用於Swing/JavaFX/昇級包等桌面應用。

加密前標準 mybatis-config.xml

<?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");
    }
}

DES 加密工具類 (簡化版)

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);
    }
}

構建時加密腳本 (Maven AntRun / Main 類)

// 開發期運行一次,生成 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");
    }
}

安全性增強建議

  1. 密鑰管理:密鑰勿硬編碼,用環境變量/密鑰服務/硬件加密模塊(HSM)
  2. 算法升級:DES已不安全,改用AES-256-GCM或ChaCha20-Poly1305
  3. 完整性校驗:存儲HMAC-SHA256防篡改
  4. 代碼混淆:ProGuard混淆EncrypDES類,增加逆向難度
  5. 純Java配置:避免XML文件,用DataSourceFactory+Configuration代碼構建,僅加密敏感屬性

純Java代碼配置 MyBatis (無XML)

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);
copyright © 萬盛學電腦網 all rights reserved