添加jasypt依赖
<!--jasypt加密-->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
配置jasypt密钥 密钥可自定义
jasypt:
encryptor:
password: Z832MVEYRTDTY452mz5
测试生成数据库连接配置的加密数据
@Slf4j
@SpringBootTest
class DemoApplicationTests {
@Autowired
private StringEncryptor encryptor;
@Test
void contextLoads() {
//mysql数据库配置加密
String url = encryptor.encrypt("jdbc:mysql://127.0.0.1:3306/test_db?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&useSSL=false&rewriteBatchedStatements=true");
String username = encryptor.encrypt("root");
String password = encryptor.encrypt("123456");
log.info("url:"+url);
log.info("username:"+username);
log.info("password:"+password);
}
}
数据库连接加密后的结果返回如下:
url:JF5KxOmUO1y36ltLa8BFy7B/0AxSxqYyhkxyBzsv71cNEUzvk7TZYjeFrNidcf9xRbhhWE1NYBGfP+cHsP9vMXZwNZ4by4+Ymo0q3tSupfrqpHsl8yPCP4oZ1ErhBZyuh6enRxF/82CQ+Je8tdMWyfxKUIqd9IGEstLxmEbFoNMryros2ju6i2eecvj58MoNRXcsMEVfqU2yJ+nnH17qNQ7wf1O5vt6czHq1BOteUpw=
username:vMNpjbzKIKdkX6U2yexLwex64DbyaCgYNG2S+ilrBKnDvAEQwSiG/NmeyKs1dbx9
password:H6a0rpG+CGCuyAtmSebWxMURuFF19Q3n/2RAY5ZbHLNgLemdHLwsMCIMPeEfLZOb
添加mysql依赖和jpa的依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
把生成的数据库连接加密数据复制到配置文件中 默认使用ENC进行包裹 也可以使用jasypt.encryptor.property.prefix='ENC(' 和jasypt.encryptor.property.suffix=')'进行自定义的前缀和后缀的配置。
spring:
datasource:
#mysql数据库连接加密后的配置 使用jasypt的ENC包裹 默认前缀为ENC( 后缀为)
url: ENC(JF5KxOmUO1y36ltLa8BFy7B/0AxSxqYyhkxyBzsv71cNEUzvk7TZYjeFrNidcf9xRbhhWE1NYBGfP+cHsP9vMXZwNZ4by4+Ymo0q3tSupfrqpHsl8yPCP4oZ1ErhBZyuh6enRxF/82CQ+Je8tdMWyfxKUIqd9IGEstLxmEbFoNMryros2ju6i2eecvj58MoNRXcsMEVfqU2yJ+nnH17qNQ7wf1O5vt6czHq1BOteUpw=)
username: ENC(vMNpjbzKIKdkX6U2yexLwex64DbyaCgYNG2S+ilrBKnDvAEQwSiG/NmeyKs1dbx9)
password: ENC(H6a0rpG+CGCuyAtmSebWxMURuFF19Q3n/2RAY5ZbHLNgLemdHLwsMCIMPeEfLZOb)
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
jasypt:
encryptor:
password: Z832MVEYRTDTY452mz5
新建一个数据库的实体测试类 使用JPA注解自动生成数据表
/**
* @author qx
* @date 2023-01-09
* @Descripion: 测试实体
*/
@Entity
@Table(name = "t_user")
@Getter
@Setter
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;
private Date birthday;
}
7.运行项目 日志显示新增了数据表 配置成功。