导入依赖

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

2.找到jasypt-1.9.2.jar所在位置,打开cmd
在这里插入图片描述
3.输入如下命令执行

java -cp  jasypt-1.9.2.jar  org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="123456" password=sad124f1f1rf1fgt5 algorithm=PBEWithMD5AndDES

input :明文密码
password:要加的盐(可自己设置)
algorithm:加密算法,这里使用 PBEWithMD5AndDES
结果如下,OUTPUT就是加密之后的密文(密码)
在这里插入图片描述

4.在application.yml文件中配置

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    username: ENC(HPPHfpHVXzNf00SQLBrjug==)
    password: ENC(F8ckXFGTF6Wu8dQ51hoNBw==)
    url: jdbc:mysql://localhost:3306/foodie-shop-dev?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=GMT%2B8
jasypt:
  encryptor:
    password: sad124f1f1rf1fgt5

5.在启动类Application.java中配置注解,配置完成

//配置数据库加密注解
@EnableEncryptableProperties

6.小结
除了加密MySQL密码的例子之外,当配置文件中有多个密码、Token等需要加密时,这个方法就比较方便了。

除了支持字符串秘钥,jasypt还支持key文件秘钥,更加安全

安全要求很高时,还可以使用jasypt默认PBEWITHHMACSHA512ANDAES_256加密算法,该算法需要安装JCE支持

7.问题

问题描述:在Spring Boot中使用jasypt-spring-boot进行加密,但是提示:

Description:
Failed to bind properties under 'spring.datasource.password' to java.lang.String:
Reason: Failed to bind properties under 'spring.datasource.password' to java.lang.String
Action:
Update your application's configuration

解决办法:

3.0.2更改了默认的加密算法,最后的办法是把版本降到2.1.2

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐