| 知乎专栏 |
Maven 配置
<!-- https://mvnrepository.com/artifact/com.github.ulisesbocchio/jasypt-spring-boot-starter --> <dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>3.0.4</version> </dependency>
生成加密信息
package cn.netkiller.controller;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PasswordController {
@Autowired
private StringEncryptor encryptor;
@Value("${test.password}")
private String cleartext;
public PasswordController() {
// TODO Auto-generated constructor stub
}
@GetMapping("/password")
public String password(@RequestParam("text") String text) {
return encryptor.encrypt(text);
}
@GetMapping("/cleartext")
public String getPassword() {
return this.cleartext;
}
}
启动 Springboot 应用
java -jar your_springboot_application.jar --jasypt.encryptor.password=123456
将文本 neo 加密
neo@MacBook-Pro-Neo ~ % curl http://localhost:8080/password\?text\=neo YrEdNoIyJlRoO+QhHGGwhxorlrc1e0B6Sk2iWwWMeUFd5AeCh3uAuxFr0FhEi3di
修改 application.properties 配置文件
test.password=ENC(YrEdNoIyJlRoO+QhHGGwhxorlrc1e0B6Sk2iWwWMeUFd5AeCh3uAuxFr0FhEi3di)
重启 Springboot 项目,检验加密是否生效
neo@MacBook-Pro-Neo ~ % curl http://localhost:8080/cleartext neo
测试环境可以将 jasypt.encryptor.password 放入配置文件,无需每次启动加入该参数。
jasypt.encryptor.password=123456 test.password=ENC(cH0s45ZDOHtbCNgVGgs0etnigdfZgvrnhdFokG9ysnvy4DK0jZFPGOqe7Myow64y)
BasicTextEncryptor 加密文本内容
package cn.netkiller;
import org.jasypt.util.text.BasicTextEncryptor;
public class Password {
public Password() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
textEncryptor.setPassword("123456");
String username = textEncryptor.encrypt("root");
String password = textEncryptor.encrypt("123456");
System.out.println("username:" + username);
System.out.println("password:" + password);
}
}