You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无Jasypt Spring的配置文件加解密:通过datasource.xml调用静态方法解密密码

Got it, let's walk through how to implement config file encryption/decryption without Jasypt in a Spring environment, using static method calls in your datasource.xml:

无Jasypt的Spring配置文件加解密实现方案

核心思路

我们会通过自定义静态解密类,在Spring数据源XML配置中直接调用其静态方法,把加密后的密码解密后注入到数据源里。整个流程是:先将明文密码加密后存入properties配置文件,再在XML配置中通过静态方法解密该加密串,最终得到明文密码供数据源使用。

1. 编写自定义解密工具类

首先实现一个包含静态解密方法的类,这里以AES对称加密为例(你可以根据需求替换为RSA等非对称加密算法)。注意要确保这个类能被Spring的类加载器找到:

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class DecryptUtils {
    // 注意:生产环境不要硬编码密钥!建议通过环境变量/密钥管理工具获取
    private static final String SECRET_KEY = "your-16-byte-secret-key"; 
    private static final String ENCRYPT_ALGORITHM = "AES";

    // 静态解密方法,供XML配置调用
    public static String decrypt(String encryptedPassword) {
        try {
            SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(), ENCRYPT_ALGORITHM);
            Cipher cipher = Cipher.getInstance(ENCRYPT_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            
            byte[] decodedBytes = Base64.getDecoder().decode(encryptedPassword);
            byte[] decryptedBytes = cipher.doFinal(decodedBytes);
            return new String(decryptedBytes);
        } catch (Exception e) {
            throw new RuntimeException("Failed to decrypt database password", e);
        }
    }

    // 可选:配套的加密方法,用来生成加密后的密码存入properties
    public static String encrypt(String plainPassword) {
        try {
            SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(), ENCRYPT_ALGORITHM);
            Cipher cipher = Cipher.getInstance(ENCRYPT_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            
            byte[] encryptedBytes = cipher.doFinal(plainPassword.getBytes());
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            throw new RuntimeException("Failed to encrypt database password", e);
        }
    }
}

2. 配置properties文件

用上面的encrypt方法生成加密后的密码,存入你的数据库配置文件(比如db.properties):

db.url=jdbc:mysql://localhost:3306/your_database
db.username=root
db.password=U2FsdGVkX1+abcdefg123456...  # 这里是加密后的密码串

3. 在datasource.xml中调用静态解密方法

在Spring数据源XML配置里,通过Spring表达式语言(SpEL)调用DecryptUtils的静态解密方法,解密加密后的密码:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 加载properties配置文件 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 配置数据源,核心是调用静态方法解密密码 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="${db.url}"/>
        <property name="username" value="${db.username}"/>
        <!-- SpEL语法:T()指定全限定类名,调用静态decrypt方法 -->
        <property name="password" value="#{T(com.your.package.DecryptUtils).decrypt('${db.password}')}"/>
        <!-- 其他数据源配置项 -->
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="initialSize" value="5"/>
        <property name="maxActive" value="20"/>
    </bean>
</beans>

关键注意事项

  • 密钥安全:绝对不要把解密密钥硬编码在代码里!生产环境建议通过环境变量、系统属性或者专业密钥管理工具(如Vault)获取密钥,避免密钥泄露。
  • 异常处理:解密方法中的异常要明确抛出,方便排查解密失败的原因(比如密钥不匹配、加密串损坏)。
  • 类路径正确性:XML配置中要写对DecryptUtils的全限定类名,否则Spring会找不到该类导致启动失败。
  • 算法选择:如果是高安全要求的场景,建议使用RSA非对称加密,避免对称加密密钥泄露后所有加密密码都被破解。

内容的提问来源于stack exchange,提问作者ij007

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 06:53:28