spring boot + jasypt 组件 加密配置文件

介绍一个加解密组件,提高一些属性配置的安全性
在maven项目中引入依赖:

<dependency>
  <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>

然后在配置文件中配置:(我这里用的是yml格式)

jasypt:
  encryptor:
    #自定义密码盐
    password: xiaobu

然后在测试类中测试:

	@Autowired
    StringEncryptor encryptor;
	
	@Test
	public void contextLoads() {
		String url = encryptor.encrypt("jdbc:mysql://127.0.0.1/table1?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true&allowMultiQueries=true");
        String name = encryptor.encrypt("你的账号");
        String password = encryptor.encrypt("你的密码");
        System.out.println(url);
        System.out.println(name);
        System.out.println(password);
        //encryptor.encrypt 加密
        //encryptor.decrypt 解密
	}

输出以下内容:

A8KuY7WX5ouaCQB5Uo+aws+nFYFnGR69h5wmksAsaww77ZDE01fD9Z0/TmzAc1faTGIiVwLkaE0O0veM+nTsGUexJqNc/Y7qym4LSiAuI04m2IvE5gMuUxQbaTy4ZYUPlJzxGP1RH7l87OrdA7ma1c6VfIRpBeeStNBLm476t0sZmdiUmzpEUg==
SbsH91c1wv0S09B1bnS3xyw7lBS2uO7o
yEeD7hMJd6cN5Ae+GzQCUijzoIDc4dui

最后将输入的内容依次复制到配置文件中:

jasypt:
  encryptor:
    property:
      prefix: "ENC@["
      suffix: "]"

注:没有配置的情况下必须要放在ENC()中

url: ENC(A8KuY7WX5ouaCQB5Uo+aws+nFYFnGR69h5wmksAsaww77ZDE01fD9Z0/TmzAc1faTGIiVwLkaE0O0veM+nTsGUexJqNc/Y7qym4LSiAuI04m2IvE5gMuUxQbaTy4ZYUPlJzxGP1RH7l87OrdA7ma1c6VfIRpBeeStNBLm476t0sZmdiUmzpEUg==)
username: ENC(SbsH91c1wv0S09B1bnS3xyw7lBS2uO7o) 
password: ENC(yEeD7hMJd6cN5Ae+GzQCUijzoIDc4dui)

源码:

// 密钥
private static final String KEY = "stae";

/**
* 加密
 * @param text 明文
 * @return     密文
 */
public static String encrypt(String text) {
	StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
	encryptor.setPassword(KEY);
	return encryptor.encrypt(text);
}

/**
 * 解密
 * @param ciphertext 密文
 * @return           明文
 */
public static String decrypt(String ciphertext) {
	StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
	encryptor.setPassword(KEY);
	return encryptor.decrypt(ciphertext);
}

大功告成
jasypt官方文档
注:同一盐同一值加密后也不一样,解密后的结果都是跟加密前相同

猜你喜欢

转载自blog.csdn.net/weixin_42118284/article/details/89511196