微服务nacos或者yml配置内容部分加密jasypt

写在最前:因业务需要把nacos配置中的部分密码加密,不能暴露在外,本想用nacos官方的插拔插件nacos-aes-encryption-plugin的,但是比较复杂且官方文档说的不清不楚所以弃用,有兴趣的可以参考。链接:https://nacos.io/zh-cn/docs/v2/plugin/config-encryption-plugin.html。遂使用第二种方法:jasypt,以下是具体用法。

1.引入依赖(版本自定):

<dependency>
   <groupId>com.github.ulisesbocchio</groupId>
   <artifactId>jasypt-spring-boot-starter</artifactId>
   <version>3.0.5</version>
</dependency>

2.yml新增配置:

jasypt:
  encryptor:
    password: U3buwRJdQ2023(随便取)
    algorithm: PBEWithMD5AndDES(固定值)
        //配置格式(不写默认ENC)
    property:
      prefix: "P["
      suffix: "]"

注:algorithm是加密算法,官方默认的加密算法是 PBEWITHHMACSHA512ANDAES_256,但是如果你用的是 JDK1.8,还用不了这个算法,JDK9以上才支持,所以可以把这个算法改成PBEWithMD5AndDES。
2.1.2版本默认加密方式为:PBEWithMD5AndDES
3.0.3版本默认加密方式为:PBEWITHHMACSHA512ANDAES_256
当引入3.0.3依赖,却没有添加相关jasypt加解密配置,而密文通过【PBEWithMD5AndDES】来加密,启动会报错。
需要切换为【PBEWITHHMACSHA512ANDAES_256】方式进行。

3.生成加密密文:


/**
     * jasypt.encryptor.password 对应 配置中心 application-dev.yml 中的密码
     */
    @Test
    public void testEnvironmentProperties() {
    
    
        System.setProperty(JASYPT_ENCRYPTOR_PASSWORD, "xxx");
        StringEncryptor stringEncryptor = new DefaultLazyEncryptor(new StandardEnvironment());

        //加密方法
        System.out.println(stringEncryptor.encrypt("123456"));
        //解密方法
        System.out.println(stringEncryptor.decrypt("saRv7ZnXsNAfsl3AL9OpCQ=="));
    }

4.修改nacos或yml配置为密文(必须得是ENC(密文)格式,若想更改前缀需配置)

spring:
  datasource:
    password: ENC(密文)

猜你喜欢

转载自blog.csdn.net/m0_49605579/article/details/132584862