SpringBoot使用jasypt实现数据库连接加解密
文章目录
第一种方式:
文章目录
1、引入依赖
<!--springboot整合jasypt--> <dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>1.18</version> </dependency>
2、编写加密工具
import org.jasypt.util.text.BasicTextEncryptor;/** * @ClassName: JasyptUtil * @Description: 数据库账号密码加密工具类 * @Author: root * @Date: 22-8-10 上午9:55 * @Version: 1.0 **/public class JasyptUtil { public static void main(String[] args) { String account = "root"; String password = "12345678"; BasicTextEncryptor encryptor = new BasicTextEncryptor(); //秘钥 encryptor.setPassword("ENCKEY"); //密码进行加密 String newAccount = encryptor.encrypt(account); String newPassword = encryptor.encrypt(password); System.out.println("加密后账号:" + newAccount); System.out.println("加密后密码:" + newPassword); }}
加密后的账号密码:
加密后账号:NX7++WwgMoLEXlJq+3+ogw==
加密后密码:hDbaOYvcZ+e7F4Y9TH0CVhBK7cVqKxpP
3、更改配置文件
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
#使用ENC包住密文
username: ENC(NX7++WwgMoLEXlJq+3+ogw==)
password: ENC(hDbaOYvcZ+e7F4Y9TH0CVhBK7cVqKxpP)
第二种方式:
1、引入依赖
<!--springboot整合jasypt,实现数据库加密连接-->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>1.18</version>
</dependency>
2、编写加密工具
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
/**
* @ClassName: JasyptUtil
* @Description: 数据库账号密码加密工具类
* @Author: root
* @Date: 22-8-10 上午9:55
* @Version: 1.0
**/
public class JasyptUtil {
public static void main(String[] arg) {
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
/*配置文件中配置如下的算法*/
standardPBEStringEncryptor.setAlgorithm("PBEWithMD5AndDES");
/*配置文件中配置的password*/
standardPBEStringEncryptor.setPassword("ENCKEY");
/*要加密的文本*/
String name = standardPBEStringEncryptor.encrypt("root");
String password = standardPBEStringEncryptor.encrypt("123456");
/*将加密的文本写到配置文件中*/
System.out.println("name=" + name);
System.out.println("password=" + password);
}
}
加密后的账号密码:
name=AgYz7dVA9l1KQG6/xdUyJw==
password=fr8LpN1wfPNfrX5dFlEWVA==
3、更改配置文件
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
#使用ENC包住密文
username: ENC(AgYz7dVA9l1KQG6/xdUyJw==)
password: ENC(fr8LpN1wfPNfrX5dFlEWVA==)
说明:以上两种方式配置后可通过如下方式指定解密密钥:
1、项目启动时指定启动参数将密钥传入:
-Djasypt.encryptor.password=ENCKEY
2、在配置文件中配置密钥值:
jasypt:
encryptor:
#可指定也可不指定
algorithm: PBEWithMD5AndDES
password: EWRREWRERWECCCXC
参考文章:
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/118645.html