Spring使用加密的属性文件

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配置文件属性内容加解密》

这篇文章很好,在项目中用到了第二种方案。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值