Spring Boot配置文件properties数据库密码加密

Spring Boot配置文件数据库密码加密

pom添加依赖

<code>        
       <dependency>
           <groupid>com.github.ulisesbocchio/<groupid>
           <artifactid>jasypt-spring-boot-starter/<artifactid>
           <version>2.0.0/<version>
       /<dependency>/<code>

配置文件

添加encryptor(盐值)

<code>jasypt:
encryptor:
  password: layanan/<code>


方式1:测试类中获得密码

<code>package com.lay;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyBlogApplicationTests {
   //根据上面配的盐值自动注入
   @Autowired
   StringEncryptor stringEncryptor;
   
   @Test
   public void encryptPwd() {
       String password="password";//要加密的密码
       String result = stringEncryptor.encrypt(password);
       //打印结果
       System.out.println(result);
  }
   
}
​/<code>

其中password是我们要加密的密码,运行测试类就会在控制台输入我们加密后的密码。

方式2:CMD控制台(推荐)

找到我们maven仓库中jasypt包所在的位置,然后打开cmd控制台

<code>java -cp  D:\\ToolsForLocalStudy\\apache-maven-3.2.3\\repo\\org\\jasypt\\jasypt\\1.9.2\\jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="password" password=layanan algorithm=PBEWithMD5AndDES
​/<code>

这里注意,input="password"中我们要加密的密码,而后面password=layanan是加密的盐值,algorithm是加密方式。

然后我们就可以得到加密后的密码。

使用密码

在application.properties或者application.yml配置文件中,使用ENC(加密后的密码)就可以了

<code># Spring Boot配置文件数据库密码加密

## pom添加依赖

```xml
     
      <dependency>
          <groupid>com.github.ulisesbocchio/<groupid>
          <artifactid>jasypt-spring-boot-starter/<artifactid>
          <version>2.0.0/<version>
      /<dependency>
```

## 配置文件

添加encryptor(盐值)

```properties
jasypt:
encryptor:

  password: layanan
```



## 方式1:测试类中获得密码

```java
package com.lay;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyBlogApplicationTests {
  //根据上面配的盐值自动注入
  @Autowired
  StringEncryptor stringEncryptor;
   
  @Test
  public void encryptPwd() {
      String password="password";//要加密的密码
      String result = stringEncryptor.encrypt(password);
      //打印结果
      System.out.println(result);
   }
   
}

```

其中`password`是我们要加密的密码,运行测试类就会在控制台输入我们加密后的密码。

## 方式2:CMD控制台(推荐)

找到我们maven仓库中jasypt包所在的位置,然后打开cmd控制台

```powershell
java -cp D:\\ToolsForLocalStudy\\apache-maven-3.2.3\\repo\\org\\jasypt\\jasypt\\1.9.2\\jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="password" password=layanan algorithm=PBEWithMD5AndDES

```

这里注意,`input="password"`中我们要加密的密码,而后面`password=layanan`是加密的盐值,`algorithm`是加密方式。


然后我们就可以得到加密后的密码。

## 使用密码

在application.properties或者application.yml配置文件中,使用`ENC(加密后的密码)`就可以了

```yaml
spring:
datasource:
  name: mysql_test
  type: com.alibaba.druid.pool.DruidDataSource
   #druid相关配置
  druid:
     #监控统计拦截的filters
    filters: stat
    driver-class-name: com.mysql.jdbc.Driver
     #基本属性
    url: jdbc:mysql://192.168.3.253:3306/lu_tale?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
     #加密用户名
    username: ENC(iUcFSsWd65AutcU7jDe2O49LmdhzWBpP)
     #加密密码
    password: ENC(PQIf5dO8x5nVYGO0msOdP/Ok7lHUdrfi)
```

​/<code>


分享到:


相關文章: