出于安全考虑,明文的数据库账号密码存在安全隐患,需要对其进行加密
这里采用jasypt进行处理
引入jasypt依赖
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
配置文件中添加password信息
jasypt:
encryptor:
password: silen
编写测试代码,得到加密结果
import org.jasypt.encryption.StringEncryptor;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class JasyptApplicationTests {
@Autowired
private StringEncryptor encryptor;
@Test
public void testEncrypt() {
System.out.println(encryptor.encrypt("root")); // iozDcujQo575YtsZ1giHl/zRZM5Si6arM8EA4wMOogG2x8L4xZIQsf7dEUSG8b9A
System.out.println("解密:"+encryptor.decrypt("iozDcujQo575YtsZ1giHl/zRZM5Si6arM8EA4wMOogG2x8L4xZIQsf7dEUSG8b9A"));
}
}
将对应的数据填入配置文件中
username: ENC(iozDcujQo575YtsZ1giHl/zRZM5Si6arM8EA4wMOogG2x8L4xZIQsf7dEUSG8b9A)
password: ENC(iozDcujQo575YtsZ1giHl/zRZM5Si6arM8EA4wMOogG2x8L4xZIQsf7dEUSG8b9A)
不想使用默认的ENC(),可自定义设置,配置文件添加代码
jasypt:
encryptor:
password: silen
property:
prefix: silen(
suffix: )
#对应加密位置则为
username: silen(iozDcujQo575YtsZ1giHl/zRZM5Si6arM8EA4wMOogG2x8L4xZIQsf7dEUSG8b9A)
password: silen(iozDcujQo575YtsZ1giHl/zRZM5Si6arM8EA4wMOogG2x8L4xZIQsf7dEUSG8b9A)
password放在配置文件中依然存在被破解的风险,可以考虑在执行jar文件的时候将该参数添加进去,执行命令如下
java -jar admin.jar --jasypt.encryptor.password=silen
若在执行3的测试代码时出现报错信息
org.jasypt.exceptions.EncryptionOperationNotPossibleException: Encryption raised an exception. A possible cause is you are using strong encryption algorithms and you have not installed the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction
解决方案:
去到官网下载了两个和安全相关的包之后问题解决。
下载地址:https://www.oracle.com/java/technologies/javase-jce8-downloads.html
下载之后放置到JAVA_HOME\jdk1.8.0_72\jre\lib\security目录底下,重新运行加解密代码问题解决。