更新时间:2022-09-13 GMT+08:00
分享

配置文件加密方案

配置文件中经常会涉及一些敏感信息,例如帐号密码等参数。这时需对这些敏感信息进行加密,提供信息安全性。

本章节介绍使用jasypt-spring-boot-starter组件进行加密的实践,以RBAC认证中涉及的帐号名和密码作为示例。

  1. 在pom文件中引入加密组件对应的依赖。
    <dependency>  
       <groupId>com.github.ulisesbocchio</groupId>  
       <artifactId>jasypt-spring-boot-starter</artifactId>  
       <version>2.1.2</version>
    </dependency>
  1. 配置密码。
    • 可将密码直接配置在配置文件(例如:application.properties)中。这种方式不安全,不建议使用。
      jasypt.encryptor.password=******

      ******请填写为实际加密使用的密码。

    • 在JVM启动参数中设置密码。
      -D jasypt.encryptor.password=******

      ******请填写为实际加密使用的密码。

  1. 实现加密方法。
      //此处设置为配置项jasypt.encryptor.password的密码
      public static String salt = "GXXX6"(用户自定义);
    
      //加密方法 
      public static String demoEncrypt(String value) {
          BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
          textEncryptor.setPassword(salt);
          return textEncryptor.encrypt(value); 
      }
    
      //测试解密是否正常 
      public static String demoDecrypt(String value) {
          BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
          textEncryptor.setPassword(salt);
          return textEncryptor.decrypt(value); 
      }
    
      public static void main(String[] args) {
          String username = demoEncrypt("root");
          System.out.println(username);
          System.out.println(username); 
      }

    此处使用的加密方法是jasypt默认的加密方法,用户也可以自定义扩展加解密方法,详情请参考jasypt官方文档描述。

  1. 使用加密后的配置项。
    可以采用如下两种方式:
    • 写入配置文件方式
      spring:
        cloud:
          servicecomb:
             credentials:
                account:
                   name: ENC(帐号名密文) 
                   password: ENC(密码密文)

      其中,帐号名密文、密码密文为3得到的结果。

      这种加密方式需要使用ENC()标记,用来识别是否启用了加密。ENC()为该加密方式的特殊标记,如果没有该标记,代表使用明文。

    • 环境变量注入方式
      spring_cloud_servicecomb_credentials_account_name = ENC(帐号名密文)
      spring_cloud_servicecomb_credentials_account_password = ENC(密码密文)

      其中,帐号名密文、密码密文为3得到的结果。

分享:

    相关文档

    相关产品