1、执行命令加密数据库密码

java -cp druid-1.2.4.jar com.alibaba.druid.filter.config.ConfigTools password

password输入你的数据库密码,输出的是加密后的结果。 输出 privateKey、publicKey、password

2、需要多个加解密时

public static void main(String[] args) throws Exception {
        
    //解密    
    String password = ConfigTools.decrypt("publicKey公钥", "密码");
    System.out.println("解密密码:" + password);

    //加密        
    password =  ConfigTools.encrypt("privateKey私钥", "密码");
    System.out.println("加密密码:" + password);

}

---------------------------------------------------

通过BasicTextEncryptorStrongTextEncryptorAES256TextEncryptor三种方式实现:

1. 添加依赖(pom.xml)
<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>3.0.5</version> <!-- 支持Spring Boot 2.7+ -->
</dependency>
2. 生成加密密码(Java代码)
import org.jasypt.util.text.*;

public class JasyptDemo {
    public static void main(String[] args) {
        String password = "DB@123"; // 待加密的数据库密码
        String secretKey = "My64BitKey#2025!"; // 64位加密密钥

        // 方式1: BasicTextEncryptor
        BasicTextEncryptor basicEncryptor = new BasicTextEncryptor();
        basicEncryptor.setPassword(secretKey);
        String basicEncrypted = basicEncryptor.encrypt(password);
        System.out.println("Basic加密: ENC(" + basicEncrypted + ")"); // 输出ENC(...)

        // 方式2: StrongTextEncryptor
        StrongTextEncryptor strongEncryptor = new StrongTextEncryptor();
        strongEncryptor.setPassword(secretKey);
        String strongEncrypted = strongEncryptor.encrypt(password);
        System.out.println("Strong加密: ENC(" + strongEncrypted + ")");

        // 方式3: AES256TextEncryptor
        AES256TextEncryptor aesEncryptor = new AES256TextEncryptor();
        aesEncryptor.setPassword(secretKey);
        String aesEncrypted = aesEncryptor.encrypt(password);
        System.out.println("AES256加密: ENC(" + aesEncrypted + ")");
    }
}
3. YML配置(application.yml)​
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb
    username: admin
    password: ENC(basicEncrypted)  # Basic方式加密值
    # password: ENC(strongEncrypted)  # Strong方式加密值
    # password: ENC(aesEncrypted)     # AES256方式加密值

jasypt:
  encryptor:
    # 按需启用对应加密器配置
    algorithm: PBEWithMD5AndDES                 # Basic算法
    # algorithm: PBEWithMD5AndTripleDES         # Strong算法
    # algorithm: PBEWithHMACSHA512AndAES_256    # AES256算法
    iv-generator-classname: org.jasypt.iv.RandomIvGenerator  # AES需启用随机IV
4. 启动应用时传入密钥​
# 通过环境变量传递密钥(推荐)
export JASYPT_PASSWORD="My64BitKey#2025!"
java -jar app.jar

# 或通过启动参数传递
java -jar -Djasypt.encryptor.password="My64BitKey#2025!" app.jar

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐