springboot密文连接数据库(mysql/redis/mongodb)

发布时间 2023-09-26 10:24:42作者: 迷路小孩

1. pom添加依赖

<!-- 数据库连接加密 -->
<dependency>
   <groupId>com.github.ulisesbocchio</groupId>
   <artifactId>jasypt-spring-boot-starter</artifactId>
   <version>2.1.2</version>
</dependency>

 

2. 启动类添加

@EnableEncryptableProperties

 

3. 配置文件添加

jasypt:
  encryptor:
    password: huanhui_erp
    algorithm: PBEWithMD5AndDES

 

4.使用JasyptTest.java生成密文(mysql , redis , mongodb 都通用)

5.将配置文件内的用户名和密码,替换为生成的密文(*必须加ENC()

 

 

-----------------------------------------------------------------------------------------------------------------------

 

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig;

public class JasyptTest {
/**
* 加密的方法
**/
public void testEncrypt() throws Exception {
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
EnvironmentPBEConfig config = new EnvironmentPBEConfig();
// 加密的算法,这个算法是默认的
config.setAlgorithm("PBEWithMD5AndDES");
config.setPassword("huanhui_erp");
standardPBEStringEncryptor.setConfig(config);
// 账号
String usernameText = "huanhui";
String encryptedUsernameText = standardPBEStringEncryptor.encrypt(usernameText);
System.out.println("账号加密");
System.out.println(encryptedUsernameText);
// 密码
String passwordText = "EVJikAII9SY6t";
String encryptedPasswordText = standardPBEStringEncryptor.encrypt(passwordText);
System.out.println("密码加密");
System.out.println(encryptedPasswordText);
// url
String urlText = "mongodb://root:huanhui#2020@172.20.21.211:27017,172.20.21.212:27017/zhhh-mp-cbm?replicaSet=rep-4b7BML&readPreference=primary&authSource=admin";
String encryptedUrlText = standardPBEStringEncryptor.encrypt(urlText);
System.out.println("url加密");
System.out.println(encryptedUrlText);
}

/**
* 解密的方法
**/
public void testDe() throws Exception {
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
EnvironmentPBEConfig config = new EnvironmentPBEConfig();
config.setAlgorithm("PBEWithMD5AndDES");
config.setPassword("huanhui_erp");
standardPBEStringEncryptor.setConfig(config);
// 加密后的账号
String usernameText = "ASbbpzDGVCXUQineXuQDqA==";
String plainUsernameText = standardPBEStringEncryptor.decrypt(usernameText);
System.out.println("账号解密");
System.out.println(plainUsernameText);
// 加密后的密码
String encryptedText = "RnCWj7ogiTAERC6ed3LV6UOY5yvU8oAP";
String plainText = standardPBEStringEncryptor.decrypt(encryptedText);
System.out.println("密码解密");
System.out.println(plainText);
// 加密后的url
String encryptedUrlText = "HIYuxtD5Cjq+FJFV/1dMbL17DXYl1sY87TmF3A4aN2/Dh6d1j+RNYRfbx6K0Qfy1x38NQBTfp/QDSBpZXT3uE+1E2sx86NJXzi";
String plainUrlText = standardPBEStringEncryptor.decrypt(encryptedUrlText);
System.out.println("url解密");
System.out.println(plainUrlText);
}

public static void main(String[] args) throws Exception {
JasyptTest test = new JasyptTest();
test.testEncrypt();
System.out.println("****");
test.testDe();
}
}