美文网首页todo
使用jasypt对SpringBoot配置文件进行加密

使用jasypt对SpringBoot配置文件进行加密

作者: firefly_ | 来源:发表于2020-10-09 14:34 被阅读0次

    参考:
    工作随笔——jasypt-spring-boot使用
    jasypt-spring-boot:加密SpringBoot的敏感配置信息
    SpringBoot(27) 整合jasypt加密yml配置文件


    • pom文件增加依赖
    <!-- jasypt 配置文件加密 -->
    <dependency>
        <groupId>com.github.ulisesbocchio</groupId>
        <artifactId>jasypt-spring-boot-starter</artifactId>
        <version>2.1.0</version>
    </dependency>
    
    • 编写工具类实现配置加密
    /**
     * jasypt工具类
     * @author wishurhere
     * @date 2020/10/9
     */
    public final class JasyptUtil {
    
        /**
         * jasypt秘钥(生产中通过jvm参数配置的方式进行设置)
         */
        private final static String PWD = "yuexin2018";
    
        private JasyptUtil() {
    
        }
    
        private static StandardPBEStringEncryptor getEncryptor() {
            StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
            // 设置秘钥
            encryptor.setPassword(PWD);
            return encryptor;
        }
    
        /**
         * 加密
         * @param clearStr 明文(同一个明文每次调用会生成不一样的加密串)
         * @return 加密后的字符串
         */
        private static String encrypt(String clearStr) {
            return getEncryptor().encrypt(clearStr);
        }
    
        /**
         * 解密
         * @param encryptedStr 密文
         * @return 解密后的字符串
         */
        private static String decrypt(String encryptedStr) {
            return getEncryptor().decrypt(encryptedStr);
        }
    
        public static void main(String[] args) {
            // 加密
            System.out.println(encrypt("eip20130412"));
            // 解密
            System.out.println(decrypt("l52ID0rzCBJry26FhJuovonC1MvGcG8Y"));
        }
    }
    
    • yml配置
    spring:
      ## 数据源配置
      datasource:
        url: jdbc:mysql://localhost:3306/my_db?connectTimeout=3000&autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useAffectedRows=true
        username: root
        # jasypt默认使用ENC()来标识加密,加载配置的时候检测到ENC()即会自动解密,也可以自定义前缀和后缀
        password: ENC(l52ID0rzCBJry26FhJuovonC1MvGcG8Y)
    
    • 通过命令行设置jvm参数配置密钥(服务器上可以配置成环境变量的方式)
    java -Djasypt.encryptor.password=yuexinprod
    
    • 服务器上可以配置成环境变量(如:JASYPT_PASSWORD )
    java -Djasypt.encryptor.password=${JASYPT_PASSWORD}
    
    • 在idea中设置jvm参数配置密钥
      -Djasypt.encryptor.password=yuexinprod
      jvm配置

    启动程序 系统会自动解密。
    如果启动后有如下报错,检查jvm参数中配置的密钥和加密时设置的值是否一致或yml文件中参数格式是否正确。
    Failed to bind properties under 'spring.datasource.password' to java.lang.String: Reason: Failed to bind properties under 'spring.datasource.password' to java.lang.String

    报错信息

    相关文章

      网友评论

        本文标题:使用jasypt对SpringBoot配置文件进行加密

        本文链接:https://www.haomeiwen.com/subject/feelpktx.html