在Spring boot開發中,需要在application.yml文件里配置數據庫的連接信息,或者在啟動時傳入數據庫密碼,如果不加密,傳明文,數據庫就直接暴露了,相當於"裸奔"了,因此需要進行加密處理才行。
第一步:引入jar包【版本隨意】
如果使用@SpringBootApplication注解啟動的項目,只需增加maven依賴,其他方式請參考如下GitHub地址的README信息:
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
我們對信息加解密是使用這個jar包的:
第二步:獲取加密串
package com.test;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig;
import org.junit.Test;
public class JasyptTest {
@Test
public void testEncrypt() throws Exception {
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
EnvironmentPBEConfig config = new EnvironmentPBEConfig();
config.setAlgorithm("PBEWithMD5AndDES"); // 加密的算法,這個算法是默認的
config.setPassword("密鑰"); // 加密的密鑰,必須為ASCll碼
standardPBEStringEncryptor.setConfig(config);
String plainText = "明文字符串";
String encryptedText = standardPBEStringEncryptor.encrypt(plainText);
System.out.println(encryptedText);
}
@Test
public void testDe() throws Exception {
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
EnvironmentPBEConfig config = new EnvironmentPBEConfig();
config.setAlgorithm("PBEWithMD5AndDES");
config.setPassword("密鑰");
standardPBEStringEncryptor.setConfig(config);
String encryptedText = "加密串";
String plainText = standardPBEStringEncryptor.decrypt(encryptedText);
System.out.println(plainText);
}
}
第三步:配置數據庫信息
加密串拿到了,現在來修改application.yml的配置,我們把加密串放在ENC(加密串)即可:
spring:
datasource:
driver-class-name: oracle.jdbc.driver.OracleDriver
url: 數據庫地址
username: 用戶名
password: ENC(密碼加密串)
第四步:配置自動解密密鑰
還要在yml中加這個密鑰的配置,在項目啟動的時候,會根據密鑰自動解密ENC(加密串)所代表的數據信息:
jasypt:
encryptor:
password: 密鑰