Spring中使用加密的属性文件
文章目录
一、PropertyPlaceHolderConfigurer
属性文件
1.1 定义属性文件application.properties
:
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/spring_enterprise
username=spring
password=spring$pass
1.2 引用属性文件
方式一:传统的配置方式:
<!-- 传统的配置方式: 引用属性文件-->
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"
p:location="classpath:application.properties"
p:fileEncoding="UTF-8"></bean>
方式二:使用context
命名空间的配置方式:
<!-- 相当域传统的 PropertySourcesPlaceholderConfigurer 配置方式-->
<context:property-placeholder location="classpath:application.properties"/>
1.3 通过占位符引用属性
<bean id="myConfig" class="com.hef.conf.MyConfig" p:username="${username}" p:url="${url}"/>
二、坑:《精通Spring4.x企业应用开发实战》中的6.3.2 使用加密的属性文件
读到这里,发现这一小节的案例代码就是坑!书中DESUtil
工具类整合到Spring中之后会报错,报错如下:
Exception in thread "main" java.lang.RuntimeException: javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
at com.hef.placeholder.DESUtils.getDecryptString(DESUtils.java:69)
将解密部分的代码,改为如下之后,不报错了,但解密后的内容是乱码:
byte[] strBytes = base64Decoder.decodeBuffer(str);
Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
iE9BLgG+AvW5eey/mSCkfQ==
5(%��!�� ��rt�(�
WaDcaYbcW5c=
=G=��:�
暂时没有找到解决方案。
三、在云栖社区上发现了一篇好的博文《spring、spring-boot配置文件属性内容加解密》
这篇文章很好,在项目中用到了第二种方案。