admin管理员组

文章数量:1639677

偶然间看到开发的项目中的配置文件的密码都是明文加密,所以决定对密码进行一下加密

1.pom.xml加入依赖

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

2.编写一个测试类

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig;
import org.junit.Test;

public class JasyptTest {

	 @Test
	    public void testEncrypt() throws Exception {
	        StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
	        EnvironmentPBEConfig config = new EnvironmentPBEConfig();
	 
	        config.setAlgorithm("PBEWithMD5AndDES");          // 加密的算法,这个算法是默认的
	        config.setPassword("Hello");                        // 加密的密钥,随便自己填写,很重要千万不要告诉别人
	        standardPBEStringEncryptor.setConfig(config);
	        String plainText = "123456";         //自己的密码
	        String encryptedText = standardPBEStringEncryptor.encrypt(plainText);
	        System.out.println(encryptedText);
	    }
	 
	    @Test
	    public void testDe() throws Exception {
	        StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
	        EnvironmentPBEConfig config = new EnvironmentPBEConfig();
	 
	        config.setAlgorithm("PBEWithMD5AndDES");
	        config.setPassword("Hello");
	        standardPBEStringEncryptor.setConfig(config);
	        String encryptedText = "uDZT5i+7Mjq5PHGFmpXmrTohbvw0E6ys";   //加密后的密码
	        String plainText = standardPBEStringEncryptor.decrypt(encryptedText);
	        System.out.println(plainText);
	    }

	
}

run一下testEncrypt()方法就是加密后的密码
反之testDe()方法就是解密。 请注意 config.setPassword(“Hello”); Hello是你自己的秘钥,一定要注意,把这个秘钥交给别人,别人就可以随便破解了。有的人可能就说了秘钥肯定是要放在配置文件里吧,明白的人一看就看出来了,但是很多攻击者看的只是明文,现在已经不是明文,能加隐秘性。

生成密码除了第二步之外还有可以使用cmd来生成密码,网上很多这种的就不再介绍了。

3.在启动类上加上@EnableEncryptableProperties注解

@SpringBootApplication()
@EnableEncryptableProperties //开启加密注解
public class IntegrationSecurityApplication {

	public static void main(String[] args) {
		SpringApplication.run(IntegrationSecurityApplication.class, args);
	}

}

4.在yml的配置文件中加入以下代码;

jasypt:
  encryptor:
    password: Hello  //你的秘钥

在有密码的地方就可以进行加密了

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    platform: mysql
    url: jdbc:mysql://1270.0.01:3308/sys_system?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=Asia/Shanghai
    username: root
    password: ENC(k4LdGE0s7Ea5maFfS92+MM7NUzTWwb4y)   //加密后的密码

注意:在粘贴你加密的密码时要把密码放在ENC()的()里面才能成功。

本文标签: 配置文件密码SpringBootyml