java 明文密码加密解密,明文加密解密处理

配置文件加密和数据库一些内容的加密存储

背景

在一些项目的设计中,密码等一些重要的东西显然是不能出现在代码和数据库中的。如果出现,这显然是不符合安全规定的。所以我们就需要加密存储和解密取出,这就用了本文的方法。

方法

本文使用Encrptor方法进行加密解密,好处是只要定义这个类以后。项目内部任意字符串都可以通过调用Encrptor方法进行加密解密,包括数据库密码。做到一步定义,万事无忧。

在配置文件中存放密钥,这里密钥随便设置

jasypt.encryptor.password=ABCDE123451

新建一个配置类ApplicationContextUtil实现ApplicationContextAware,获取application.properties的配置内容

@Configuration

public class ApplicationContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public static T get(Class clazz) { return applicationContext.getBean(clazz); } public static Object get(String name) { return applicationContext.getBean(name); }

}1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

创建明文加解密类 Encryptor

public class Encryptor { public static String getEncryptorPassword() { Environment environment = ApplicationContextUtil.get(Environment.class); String encryptorPassword = environment.getProperty("jasypt.encryptor.password"); return encryptorPassword; } public static String encrypt(String orgStr) { BasicTextEncryptor textEncryptor = new BasicTextEncryptor(); textEncryptor.setPassword(getEncryptorPassword()); return textEncryptor.encrypt(orgStr); } public static String decrypt(String orgStr) { BasicTextEncryptor textEncryptor = new BasicTextEncryptor(); textEncryptor.setPassword(getEncryptorPassword()); return textEncryptor.decrypt(orgStr); }

}1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

做完以上步骤就算完成了,由于是静态方法,只需要“哪里不会点哪里了”。下面给几个示例。

//密码加密存储

Encryptor.encrypt(systemUser.getPassword())

//登陆时密码解密取出

Encryptor.decrypt(systemUser.getPassword())1

2

3

4

另外对于想加密配置文件,比如数据库密码想以密文显示,只需要先把原密码加密输出

System.out.println("ENC(" + textEncryptor.encrypt("password") + ")");1

得到密文后在配置文件里这样写,系统自动就能读懂,你的密码是加密过的了

spring.datasource.password=ENC(得到的加密过的密文)1

可能出现的问题

Failed to bind properties under

Description:

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

Update your application's configuration1

2

3

4

5

6

7

解决办法: 发现是3.0.3更改了默认的加密算法,最后的办法是把版本降到2.1.2

文章来源: blog.csdn.net,作者:Jeter-JT.Zhao,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/zjt11112/article/details/114628789

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值