jasypt对springboot加密使用
1.版本说明及引用
因为考虑到我的项目springboot-boot-starter是2.3.3RELEASE版本,所以关于jasypt使用的是jasypt-spring-boot-starter
2.1.2版本。
即
<!-- https://mvnrepository.com/artifact/com.github.ulisesbocchio/jasypt-spring-boot-starter -->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
springboot
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3RELEASE</version>
</parent>
2:配置yml
yml中添加如下加盐处理,properties自行转化
其中这个password只是为了对你的要加密解密的字符串加盐,非真正要加密的串。
jasypt:
encryptor:
password: 71144850f4fb4cc55fc0ee6935badddf
3:controller测试:
import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
public class TestController extends CommonController {
@Autowired
private StringEncryptor encryptor;
/**
* 测试jasypt加密解密
*/
@GetMapping("/jasypt")
public void testJasypt() {
String password = "123456";
String encryptPwd = encryptor.encrypt(password);
System.out.println("encryption: " + encryptPwd);
System.out.println("decryption: " + encryptor.decrypt(encryptPwd));
}
}
结果
Test Unit4测试:
import com.ericsson.bit.sqa.BITOauth2Application;
import org.jasypt.encryption.StringEncryptor;
import org.junit.jupiter.api.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.SpringJUnit4ClassRunner;
/**
* @author eujiunc
* @date 2021-01-22 13:43:58
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = BITOauth2Application.class)
public class JasyptUtilTest {
@Autowired
private StringEncryptor encryptor;
@Test
public void jasypt(){
String name = encryptor.encrypt("hello");
System.out.println("en: " + name);
System.out.println("de: " + encryptor.decrypt(name));
}
}
结果
4:yml配置解密
对要加密的敏感信息进行jasypt加密处理后,需要在配置文件用ENC(加密串)进行配置文件加密。
这样即可正常启动程序而达到配置文件加密的目的。
5:注意:如果没在配置中配置加盐会出现如下错误
[2021-01-22 13:55:33][ERROR][ANONYMOUS] Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: either 'jasypt.encryptor.password' or one of ['jasypt.encryptor.private-key-string', 'jasypt.encryptor.private-key-location'] must be provided for Password-based or Asymmetric encryption] with root cause
java.lang.IllegalStateException: either 'jasypt.encryptor.password' or one of ['jasypt.encryptor.private-key-string', 'jasypt.encryptor.private-key-location'] must be provided for Password-based or Asymmetric encryption