Spring Boot 配置文件这样加密,才足够安全

Spring Boot 配置文件这样加密,才足够安全

1.前景

在使用Springboot时,通常很多信息都是在application.yml中直接明文配置的,比如数据库链接信息,redis链接信息等等。但是这样是不安全的。

所以需要对敏感数据进行加密,这样防止密码泄露

Jasypt这个库为我们解决了这个问题,实现了springboot配置的自定加密加密

2.简单使用

源码对应地址:

http://gitlab.sea-clouds.cn/csdn/spring-boot-csdn/-/tree/master/05-spring-boot-jasypt

2.1引入依赖

<properties><maven.compiler.source>11</maven.compiler.source><maven.compiler.target>11</maven.compiler.target></properties><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>2.4.0</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><dependencies><!–web和测试–><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><scope>test</scope></dependency><!–jdbc–><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!–jasypt加密–><dependency><groupId>com.github.ulisesbocchio</groupId><artifactId>jasypt-spring-boot-starter</artifactId><version>3.0.3</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies>2.2配置application信息

jasypt配置

jasypt:encryptor:#加密算法algorithm:PBEWITHHMACSHA512ANDAES_256#加密使用的盐password:jaspyt_password2.3加密解密测试

/*@authorHLH@description:加密解密测试/@SpringBootTest@RunWith(SpringRunner.class)publicclassJasyptTest{@AutowiredprivateStringEncryptorstringEncryptor;/加密解密测试/@TestpublicvoidjasyptTest(){//加密System.out.println(stringEncryptor.encrypt(“root”));//JSrINYe4IBotHndGjX1hnmY3mtPNUJlXjP12cx1+pHqUz2FNXGPu3Frnajh3QCXg//解密System.out.println(stringEncryptor.decrypt(“JSrINYe4IBotHndGjX1hnmY3mtPNUJlXjP12cx1+pHqUz2FNXGPu3Frnajh3QCXg”));//root}/*手动测试*/@Testpublicvoidtest(){PooledPBEStringEncryptorencryptor=newPooledPBEStringEncryptor();SimpleStringPBEConfigconfig=newSimpleStringPBEConfig();config.setPassword(“jaspyt_password”);config.setAlgorithm(“PBEWITHHMACSHA512ANDAES_256”);config.setKeyObtentionIterations(“1000”);config.setPoolSize(“1”);config.setProviderName(“SunJCE”);config.setSaltGeneratorClassName(“org.jasypt.salt.RandomSaltGenerator”);config.setIvGeneratorClassName(“org.jasypt.iv.RandomIvGenerator”);config.setStringOutputType(“base64”);encryptor.setConfig(config);System.out.println(encryptor.encrypt(“root”));//JSrINYe4IBotHndGjX1hnmY3mtPNUJlXjP12cx1+pHqUz2FNXGPu3Frnajh3QCXg}}3.使用Jasypt加密后的字符串代替数据库密码3.1使用加密类进行加密

密码root加密之后XjYnpGd3JGICnxumpFcfRP8J83m265yC/r1FiwLr9Yo1PNbPXQ2xykLHPpy02CZ1

/数据库密码加密/@TestpublicvoidencryptPasswored(){//加密System.out.println(stringEncryptor.encrypt(“root”));//XjYnpGd3JGICnxumpFcfRP8J83m265yC/r1FiwLr9Yo1PNbPXQ2xykLHPpy02CZ1//解密System.out.println(stringEncryptor.decrypt(“XjYnpGd3JGICnxumpFcfRP8J83m265yC/r1FiwLr9Yo1PNbPXQ2xykLHPpy02CZ1”));//root}3.2替换数据库配置

spring:datasource:driver-class-name:com.mysql.cj.jdbc.Driverurl:jdbc:mysql://192.168.10.31/mpusername:root#使用ENC()包裹,标识为加密之后的,否则无法解密,会报错password:ENC(R2H69h1aEgJ3EDPLXAVQ5CxZJWtl8EvqIJUtlATRt6om4w46/J+blu2JAvkR7Yvp)3.3测试

@AutowiredprivateDataSourcedataSource;/*测试加密之后的数据源使用是否正常查看是否能正常获取链接/@TestpublicvoiddatasourceTest()throwsSQLException{Connectionconnection=dataSource.getConnection();System.out.println(connection);//HikariProxyConnection@1487059223wrappingcom.mysql.cj.jdbc.ConnectionImpl@48904d5aconnection.close();}4.Jasypt配置详解

所有配置都在JasyptEncryptorConfigurationProperties类中定义,我们只需要在yml中配置属性,即可达到重写的目的

Jasypt使用StringEncryptor来解密属性。如果Spring上下文中找不到自定义的StringEncryptor,就会自动创建一个,可以通过以下属性进行配置

唯一需要的属性是加密的盐,其余的可以使用默认值。虽然所有这些属性都可以在属性文件中生命,但加密所使用的盐不应该存储在属性文件中,而是应该通过系统属性、命令行参数或者环境变量传递,只要他的名称是jasypt.encryptor.password,它就可以工作。

倒数第二个属性jasypt.encryptor.proxyPropertySources用于只是jasyptspringboot如何拦截属性值进行解密。默认值false使用PropertySource、EnumerablePropertySource和MapPropertySource的自定义包装器实现。当为true时,拦截机制将在每个特定的PropertySource实现上使用CGLib代理。在某些必须保留原始PropertySource类型的场景中,这可能很有用。

5.自定义加密

默认情况下,bean容器会配置LazyJasyptSringEncryptor

5.1官方配置

官方配置的Bean都是在EncryptablePropertyResolverConfiguration中进行注入的

@Bean(name={“lazyJasyptStringEncryptor”})publicStringEncryptorstringEncryptor(EnvCopyenvCopy,BeanFactorybf){StringcustomEncryptorBeanName=envCopy.get().resolveRequiredPlaceholders(ENCRYPTOR_BEAN_PLACEHOLDER);booleanisCustom=envCopy.get().containsProperty(“jasypt.encryptor.bean”);returnnewDefaultLazyEncryptor(envCopy.get(),customEncryptorBeanName,isCustom,bf);}5.2自定义加密

可以在Spring上下文中共自定义自己的StringEncryptorBean,默认的加密程序将被忽略

注意

自定义Bean的名称必须为jasyptStringEncryptor,否则解密不生效

自定义注入bean

/*加入StringEncryptor加密解密类*beanName必须为jasyptStringEncryptor才能是自定义的生效configProps为jasypt框架中读取的配置类,就不用自己读取了/@Bean(“jasyptStringEncryptor”)publicStringEncryptorjasyptStringEncryptor(Singleton<JasyptEncryptorConfigurationProperties>configProps){PooledPBEStringEncryptorencryptor=newPooledPBEStringEncryptor();JasyptEncryptorConfigurationPropertiesjasyptProperties=configProps.get();SimpleStringPBEConfigconfig=newSimpleStringPBEConfig();config.setPassword(jasyptProperties.getPassword());config.setAlgorithm(jasyptProperties.getAlgorithm());config.setKeyObtentionIterations(jasyptProperties.getKeyObtentionIterations());config.setPoolSize(jasyptProperties.getPoolSize());config.setProviderName(jasyptProperties.getProviderName());config.setSaltGeneratorClassName(jasyptProperties.getSaltGeneratorClassname());config.setIvGeneratorClassName(jasyptProperties.getIvGeneratorClassname());config.setStringOutputType(jasyptProperties.getStringOutputType());encryptor.setConfig(config);returnencryptor;}6.自定义属性探测器

属性探测器为判断一个属性值是否为加密后的字符串,并且截取真实字符串

6.1官方处理流程

6.1.2注入

在EncryptablePropertyResolverConfiguration类中

@Bean(name={“lazyEncryptablePropertyDetector”})publicEncryptablePropertyDetectorencryptablePropertyDetector(EnvCopyenvCopy,BeanFactorybf){StringcustomDetectorBeanName=envCopy.get().resolveRequiredPlaceholders(DETECTOR_BEAN_PLACEHOLDER);booleanisCustom=envCopy.get().containsProperty(“jasypt.encryptor.property.detector-bean”);returnnewDefaultLazyPropertyDetector(envCopy.get(),customDetectorBeanName,isCustom,bf);}

6.1.2DefaultLazyPropertyDetector

默认实现是DefaultLazyPropertyDetector,具体代码是

@Slf4jpublicclassDefaultLazyPropertyDetectorimplementsEncryptablePropertyDetector{//属性探测器privateSingleton<EncryptablePropertyDetector>singleton;publicDefaultLazyPropertyDetector(ConfigurableEnvironmentenvironment,StringcustomDetectorBeanName,booleanisCustom,BeanFactorybf){singleton=newSingleton<>(()->Optional.of(customDetectorBeanName).filter(bf::containsBean).map(name->(EncryptablePropertyDetector)bf.getBean(name)).map(tap(bean->log.info(“FoundCustomDetectorBean{}withname:{}”,bean,customDetectorBeanName))).orElseGet(()->{if(isCustom){thrownewIllegalStateException(String.format(“PropertyDetectorcustomBeannotfoundwithname‘%s’”,customDetectorBeanName));}log.info(“PropertyDetectorcustomBeannotfoundwithname‘{}’.InitializingDefaultPropertyDetector”,customDetectorBeanName);returncreateDefault(environment);}));}publicDefaultLazyPropertyDetector(ConfigurableEnvironmentenvironment){//创建一个属性探测器singleton=newSingleton<>(()->createDefault(environment));}privateDefaultPropertyDetectorcreateDefault(ConfigurableEnvironmentenvironment){//读取所有的属性JasyptEncryptorConfigurationPropertiesprops=JasyptEncryptorConfigurationProperties.bindConfigProps(environment);//创建一个默认的属性探测器,读取配置文件中的前缀和后缀returnnewDefaultPropertyDetector(props.getProperty().getPrefix(),props.getProperty().getSuffix());}/*是否为解密格式字符串*/@OverridepublicbooleanisEncrypted(Stringproperty){returnsingleton.get().isEncrypted(property);}/获取真是的加密后的字符串/@OverridepublicStringunwrapEncryptedValue(Stringproperty){returnsingleton.get().unwrapEncryptedValue(property);}}

在其中是创建了一个DefaultPropertyDetector对象

6.1.3DefaultPropertyDetector

publicclassDefaultPropertyDetectorimplementsEncryptablePropertyDetector{//默认前缀和后缀privateStringprefix=“ENC(”;privateStringsuffix=“)”;publicDefaultPropertyDetector(){}publicDefaultPropertyDetector(Stringprefix,Stringsuffix){Assert.notNull(prefix,“Prefixcan‘tbenull”);Assert.notNull(suffix,“Suffixcan’tbenull”);this.prefix=prefix;this.suffix=suffix;}@OverridepublicbooleanisEncrypted(Stringproperty){if(property==null){returnfalse;}finalStringtrimmedValue=property.trim();return(trimmedValue.startsWith(prefix)&&trimmedValue.endsWith(suffix));}//去掉前缀和后缀@OverridepublicStringunwrapEncryptedValue(Stringproperty){returnproperty.substring(prefix.length(),(property.length()-suffix.length()));}}6.2自定义规则探测器

两种方式自定义

提供一个名为encryptablePropertyDetector的EncryptablePropertyDetector类型的Bean来覆盖默认的实现如果提供的bean名称不为encryptablePropertyDetector,可以通过修改yml中的属性jasypt.encryptor.property.detector-Bean为自己的bean的名称。

方式

要么自定义类要么修改yml中的前缀和后缀

6.2.1自定义属性探测器,加入容器

/*自定义属性探测器beanName为encryptablePropertyDetector/@Bean(name=“encryptablePropertyDetector”)publicEncryptablePropertyDetectorencryptablePropertyDetector(){returnnewMyEncryptablePropertyDetector();}/@authorHLH@description:自定义的属性探测器@email17703595860@163.com@date:Createdin2021/8/1920:01*/publicclassMyEncryptablePropertyDetectorimplementsEncryptablePropertyDetector{/*是否为可以解密的字符串@paramvalue全部的字符串@return是否是解密的字符串,true,是,false,否*/@OverridepublicbooleanisEncrypted(Stringvalue){if(value!=null){returnvalue.startsWith(“ENC@”);//自定义规则为ENC@开头}returnfalse;}/截取到除了标识之后的值@paramvalue带前缀@returnstring去掉标识符的字符串/@OverridepublicStringunwrapEncryptedValue(Stringvalue){returnvalue.substring(“ENC@”.length());//截取ENC@之后的字符串}}

yml中的配置

jasypt:encryptor:#加密算法algorithm:PBEWITHHMACSHA512ANDAES_256#加密使用的盐password:jaspytpasswordproperty:#修改默认的前缀和后缀,如果自定义属性探测器,那么此项配置不起作用#prefix:ENC(#suffix:)#自定义的属性探测器,如果这个是自定义的,那么上述的前缀后缀不生效detector-bean:encryptablePropertyDetector

6.2.2修改yml中的配置

spring:datasource:driver-class-name:com.mysql.cj.jdbc.Driverurl:jdbc:mysql://192.168.10.31/mpusername:root#使用ENC()包裹,标识为加密之后的,否则无法解密,会报错#自定义规则之后,使用ENC@开头password:ENC@JSrINYe4IBotHndGjX1hnmY3mtPNUJlXjP12cx1+pHqUz2FNXGPu3Frnajh3QCXg7.自定义规则的前缀和后缀

在上述说明中,在DefaultLazyPropertyDetector中是默认是通过配置文件中的规则进行匹配的。默认规则是以ENC(开头,以)结尾,可以复写配置来自定义前缀和后缀

上面第6条是自定义了属性探测器,包括了定义规则和过滤字符串

如果只是想自定义前缀和后缀,那么可以直接修改yml中的配置来修改自定义的前缀和后缀

jasypt:encryptor:#加密算法algorithm:PBEWITHHMACSHA512ANDAES_256#加密使用的盐password:jaspyt_passwordproperty:#修改默认的前缀和后缀,如果自定义属性探测器,那么此项配置不起作用prefix:ENC(suffix:)8.直接自定义解密规则

上述6和7自定义了解密字符串的规则和解密字符串的过滤,但是真正的解析处理还是Jasypt框架来负责的。我们也可以直接自定义解密的一系列流程。

8.1官方处理流程

8.1.1官方的注入

在EncryptablePropertyResolverConfiguration类中

@Bean(name={“lazyEncryptablePropertyResolver”})publicEncryptablePropertyResolverencryptablePropertyResolver(@Qualifier(“lazyEncryptablePropertyDetector”)EncryptablePropertyDetectorpropertyDetector,@Qualifier(“lazyJasyptStringEncryptor”)StringEncryptorencryptor,BeanFactorybf,EnvCopyenvCopy,ConfigurableEnvironmentenvironment){StringcustomResolverBeanName=envCopy.get().resolveRequiredPlaceholders(RESOLVER_BEAN_PLACEHOLDER);booleanisCustom=envCopy.get().containsProperty(“jasypt.encryptor.property.resolver-bean”);returnnewDefaultLazyPropertyResolver(propertyDetector,encryptor,customResolverBeanName,isCustom,bf,environment);}

默认注入的是DefaultLazyPropertyResolver但是在其中创建的是EncryptablePropertyResolver对象

8.1.2EncryptablePropertyResolver

官方默认是通过EncryptablePropertyResolver接口来处理解析字符串的

publicinterfaceEncryptablePropertyResolver{/*处理所有属性的解密处理*如果为检测到加密规则,那么返回实际为相同的字符创@paramvalue属性值@return如果值未加密,返回原值,如果加密,返回加密之后的值/StringresolvePropertyValue(Stringvalue);}其真实性使用的实现类是DefaultPropertyResolver用来真正处理解析。就是通过调用上文中的StringEncryptor处理解密,使用EncryptablePropertyDetector定义的解密字符串规则定义是否为加密的字符串

publicclassDefaultPropertyResolverimplementsEncryptablePropertyResolver{privatefinalEnvironmentenvironment;//默认的或者自定义的StringEncryptor,用来解密privateStringEncryptorencryptor;//默认的或者自定义的EncryptablePropertyDetector,用来定义是否为加密的字符串privateEncryptablePropertyDetectordetector;publicDefaultPropertyResolver(StringEncryptorencryptor,Environmentenvironment){this(encryptor,newDefaultPropertyDetector(),environment);}publicDefaultPropertyResolver(StringEncryptorencryptor,EncryptablePropertyDetectordetector,Environmentenvironment){this.environment=environment;Assert.notNull(encryptor,“Stringencryptorcan‘tbenull”);Assert.notNull(detector,“EncryptablePropertydetectorcan’tbenull”);this.encryptor=encryptor;this.detector=detector;}@OverridepublicStringresolvePropertyValue(Stringvalue){returnOptional.ofNullable(value).map(environment::resolvePlaceholders).filter(detector::isEncrypted)//如果经过属性探测器确认的,才继续.map(resolvedValue->{try{StringunwrappedProperty=detector.unwrapEncryptedValue(resolvedValue.trim());//过滤加密规则后的字符串StringresolvedProperty=environment.resolvePlaceholders(unwrappedProperty);returnencryptor.decrypt(resolvedProperty);//解密}catch(EncryptionOperationNotPossibleExceptione){thrownewDecryptionException(“Unabletodecrypt:”+value+“.DecryptionofPropertiesfailed,makesureencryption/decryption”+“passwordsmatch”,e);}}).orElse(value);}}8.2自定义的解密逻辑

编写自己的解密逻辑类

加入spring容器,命名为encryptablePropertyResolver,或者通过yml方式配置自定义bean名称

@Bean(“encryptablePropertyResolver”)publicEncryptablePropertyResolverencryptablePropertyResolver(StringEncryptorjasyptStringEncryptor,EncryptablePropertyDetectorencryptablePropertyDetector){returnnewMyEncryptablePropertyResolver(jasyptStringEncryptor,encryptablePropertyDetector);}/*@authorHLH@description:直接自定义解密规则@email17703595860@163.com@date:Createdin2021/8/2121:22/publicclassMyEncryptablePropertyResolverimplementsEncryptablePropertyResolver{//处理解密privatefinalStringEncryptorencryptor;//属性探测器privatefinalEncryptablePropertyDetectordetector;publicMyEncryptablePropertyResolver(StringEncryptorencryptor,EncryptablePropertyDetectordetector){this.encryptor=encryptor;this.detector=detector;}/处理真正的解密逻辑@paramvalue原始值@return如果值未加密,返回原值,如果加密,返回加密之后的值/@OverridepublicStringresolvePropertyValue(Stringvalue){returnOptional.ofNullable(value).filter(detector::isEncrypted)//如果经过属性探测器确认的,才继续.map(resolvedValue->{try{StringunwrappedProperty=detector.unwrapEncryptedValue(resolvedValue.trim());//过滤加密规则后的字符串returnencryptor.decrypt(unwrappedProperty);//解密}catch(EncryptionOperationNotPossibleExceptione){thrownewDecryptionException(“Unabletodecrypt:”+value+“.DecryptionofPropertiesfailed,makesureencryption/decryption”+“passwordsmatch”,e);}}).orElse(value);}}

yml配置

jasypt:encryptor:#加密算法algorithm:PBEWITHHMACSHA512ANDAES_256#加密使用的盐password:jaspytpasswordproperty:#修改默认的前缀和后缀,如果自定义属性探测器,那么此项配置不起作用#prefix:ENC(#suffix:)#自定义的属性探测器,如果这个是自定义的,那么上述的前缀后缀不生效detector-bean:encryptablePropertyDetector#自定义解密逻辑类如果配置了,默认的解析器将不工作resolver-bean:encryptablePropertyResolver9.自定义过滤器

在Jasypt-spring-boot中,引入了过滤器

过滤器filter允许过滤某些属性,不进行解密。默认情况下,jasypt.encryptor开头的所有属性都会将从检查项中排除掉。这是为了配置Bean,在加载时循环依赖

9.1默认处理流程

9.1.1官方的注入

在EncryptablePropertyResolverConfiguration类中

@Bean(name={“lazyEncryptablePropertyFilter”})publicEncryptablePropertyFilterencryptablePropertyFilter(EnvCopyenvCopy,ConfigurableBeanFactorybf){StringcustomFilterBeanName=envCopy.get().resolveRequiredPlaceholders(FILTER_BEAN_PLACEHOLDER);booleanisCustom=envCopy.get().containsProperty(“jasypt.encryptor.property.filter-bean”);returnnewDefaultLazyPropertyFilter(envCopy.get(),customFilterBeanName,isCustom,bf);}

于上面的逻辑一样,在DefaultLazyPropertyFilter中其实是新建了一个EncryptablePropertyFilter对象,默认实现类是DefaultPropertyFilter

9.1.2DefaultPropertyFilter

publicclassDefaultPropertyFilterimplementsEncryptablePropertyFilter{//过滤的和包含的,优先读取配置文件的privatefinalList<String>includeSourceNames;privatefinalList<String>excludeSourceNames;privatefinalList<String>includePropertyNames;privatefinalList<String>excludePropertyNames;publicDefaultPropertyFilter(){includeSourceNames=null;includePropertyNames=null;excludeSourceNames=null;excludePropertyNames=null;}publicDefaultPropertyFilter(List<String>includeSourceNames,List<String>excludeSourceNames,List<String>includePropertyNames,List<String>excludePropertyNames){this.includeSourceNames=includeSourceNames;this.excludeSourceNames=excludeSourceNames;this.includePropertyNames=includePropertyNames;this.excludePropertyNames=excludePropertyNames;}//是否拦截@OverridepublicbooleanshouldInclude(PropertySource<?>source,Stringname){//如果上述四个都没有配置,那么全部放行if(isIncludeAll()){returntrue;}//如果是不包含的,返回false,就过滤掉了if(isMatch(source.getName(),excludeSourceNames)||isMatch(name,excludePropertyNames)){returnfalse;}//如果是包含的,就放行returnisIncludeUnset()||isMatch(source.getName(),includeSourceNames)||isMatch(name,includePropertyNames);}privatebooleanisIncludeAll(){returnisIncludeUnset()&&isExcludeUnset();}privatebooleanisIncludeUnset(){returnisEmpty(includeSourceNames)&&isEmpty(includePropertyNames);}privatebooleanisExcludeUnset(){returnisEmpty(excludeSourceNames)&&isEmpty(excludePropertyNames);}privatebooleanisEmpty(List<String>patterns){returnpatterns==null||patterns.isEmpty();}//传递的配置其实是正则,进行正则匹配privatebooleanisMatch(Stringname,List<String>patterns){returnname!=null&&!isEmpty(patterns)&&patterns.stream().anyMatch(name::matches);}}9.2自定义过滤器

方式

要么自定义过滤器要么修改jasypt.encryptor.property.include-names或者jasypt.encryptor.property.exclude-names配置拦截和放行的资源key

自定义过滤器类

加入spring容器,命名为encryptablePropertyFilter

/*自定义的属性拦截器@paramconfigPropsJasypt官方读取的配置集合@return自定义属性拦截器*/@Bean(name=“encryptablePropertyFilter”)publicEncryptablePropertyFilterencryptablePropertyFilter(Singleton<JasyptEncryptorConfigurationProperties>configProps){returnnewMyEncryptablePropertyFilter(configProps.get());}/@authorHLH@description:自定义的属性过滤器@email17703595860@163.com@date:Createdin2021/8/2213:37/publicclassMyEncryptablePropertyFilterimplementsEncryptablePropertyFilter{/**jasypt的所有配置/JasyptEncryptorConfigurationPropertiesjasyptProperties;publicMyEncryptablePropertyFilter(JasyptEncryptorConfigurationPropertiesjasyptProperties){this.jasyptProperties=jasyptProperties;}@OverridepublicbooleanshouldInclude(PropertySource<?>source,Stringname){List<String>excludeNames=jasyptProperties.getProperty().getFilter().getExcludeNames();List<String>includeNames=jasyptProperties.getProperty().getFilter().getIncludeNames();if(CollectionUtils.isEmpty(includeNames)&&CollectionUtils.isEmpty(excludeNames)){returntrue;}if(isMatch(source.getName(),excludeNames)||isMatch(source.getName(),excludeNames)){returnfalse;}returnCollectionUtils.isEmpty(includeNames)||isMatch(source.getName(),includeNames)||isMatch(name,includeNames);}/**正则判断,如果满足,返回true,如果不满足,返回false@paramname配置的key@parampatterns正则列表@return如果满足,返回true,如果不满足,返回false*/privatebooleanisMatch(Stringname,List<String>patterns){returnname!=null&&!CollectionUtils.isEmpty(patterns)&&patterns.stream().anyMatch(name::matches);}}

yml配置

jasypt:encryptor:#加密算法algorithm:PBEWITHHMACSHA512ANDAES_256#加密使用的盐password:jaspytpasswordproperty:#修改默认的前缀和后缀,如果自定义属性探测器,那么此项配置不起作用#prefix:ENC(#suffix:)#自定义的属性探测器,如果这个是自定义的,那么上述的前缀后缀不生效detector-bean:encryptablePropertyDetector#自定义解密逻辑类如果配置了,默认的解析器将不工作resolver-bean:encryptablePropertyResolver#过滤器的beanfilter-bean:encryptablePropertyFilter#过滤器配置,正则filter:#默认包含的include-names:#默认拦截的,默认拦截jasypt.encryptor的配置exclude-names:-^jasypt.encryptor.*10.使用mvn插件加密解密

使用代码的方式比较不方便,还需要编码实现,如果不想编码,简单的进行加密解密,就可以使用maven的插件,使用mvn命令进行加密解密

10.1引入Jasypt的maven插件

<build><plugins><!–Jasypt的maven插件–><plugin><groupId>com.github.ulisesbocchio</groupId><artifactId>jasypt-maven-plugin</artifactId><version>3.0.2</version></plugin></plugins></build>10.2加密

使用jasypt-maven-plugin插件加密明文密码:(如果配置项是默认值,可以不指定)

mvnjasypt:encrypt-value-Djasypt.encryptor.password=“jaspyt_password”-Djasypt.plugin.value=“root”-Djasypt.encryptor.algorithm=“PBEWITHHMACSHA512ANDAES_256”jasypt.encryptor.password是秘钥,尽量复杂!不能放在代码和配置文件里面!不能泄漏jasypt.plugin.value是要加密的明文密码jasypt.encryptor.algorithm默认加密算法是PBEWITHHMACSHA512ANDAES_256,需要有JCE(JavaCryptographyExtension)支持,如果不想安装JCE,可以使用PBEWithMD5AndDES算法。windows下的jdk自带

进入项目所在的目录,输入命令,成功加密

10.3解密

使用jasypt-maven-plugin插件解密密文密码:(如果配置项是默认值,可以不指定)

mvnjasypt:decrypt-value-Djasypt.encryptor.password=“jaspyt_password”-Djasypt.plugin.value=“pqsp6kvVfBcKoEltxP9MilGGRo8EE506mDWAuTFIKePDXMeArta13bT6Hl8QqVlC”-Djasypt.encryptor.algorithm=“PBEWITHHMACSHA512ANDAES_256”jasypt.encryptor.password是秘钥,尽量复杂!不能放在代码和配置文件里面!不能泄漏jasypt.plugin.value是要加密的明文密码,有ENC()包裹或者不包裹都可以jasypt.encryptor.algorithm默认加密算法是PBEWITHHMACSHA512ANDAES_256,需要有JCE(JavaCryptographyExtension)支持,如果不想安装JCE,可以使用PBEWithMD5AndDES算法。windows下的jdk自带

进入项目所在的目录,输入命令,成功加密

11.思维导图

最后再来一张思维导图

原文链接:https://mp.weixin.qq.com/s/CN2niF4yTpOs3cZYBcWDeQ

本站所有文章资讯、展示的图片素材等内容均为注册用户上传(部分报媒/平媒内容转载自网络合作媒体),仅供学习参考。 用户通过本站上传、发布的任何内容的知识产权归属用户或原始著作权人所有。如有侵犯您的版权,请联系我们反馈本站将在三个工作日内改正。