保证项目中的账号密码不以明文的形式展示
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.4</version>
</dependency>
import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableEncryptableProperties
public class AdminMain {
public static void main(String[] args) {
SpringApplication.run(AdminMain.class, args);
}
}
这里以配置数据库为例:
jasypt:
encryptor:
password: 02700083-9fd9-4b82-a4b4-9177e0560e92
algorithm: PBEWithMD5AndDES
iv-generator-classname: org.jasypt.iv.NoIvGenerator
生成账号:root,密码:mysql
import org.jasypt.util.text.BasicTextEncryptor;
/**
*@description:
*@author: alex
*@createDate: 2022/7/28 19:58
*@version: 1.0.0
*/
public class Test {
public static void main(String[] args) {
//该类的选择根据algorithm:PBEWithMD5AndDE选择的算法选择
BasicTextEncryptor encryptor = new BasicTextEncryptor();
encryptor.setPassword("02700083-9fd9-4b82-a4b4-9177e0560e92");
String encrypt = encryptor.encrypt("root");
System.out.println(encrypt);
String decrypt = encryptor.decrypt(encrypt);
System.out.println(decrypt);
String encrypt = encryptor.encrypt("mysql");
System.out.println(encrypt);
String decrypt = encryptor.decrypt(encrypt);
System.out.println(decrypt);
}
}
##生成的结果,每次生成的结果都不一致
Ii5Ux7xKBVTd7+SrCkX9TQ==
root
Eg/vK2yi3/p8boYVznsyVw==
mysql
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/xxx?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
username: ENC(Ii5Ux7xKBVTd7+SrCkX9TQ==)
password: ENC(Eg/vK2yi3/p8boYVznsyVw==)
1.如果启动项目的时候报如下错误:
Failed to bind properties under 'spring.datasource.username' to java.lang.String:
Reason: Failed to bind properties under 'spring.datasource.username' to java.lang.String
可以通过配置yaml文件
jasypt:
encryptor:
iv-generator-classname: org.jasypt.iv.NoIvGenerator