赞
踩
在服务中不可避免的需要使用到一些秘钥(数据库、redis等)开发和测试环境还好,但生产如果采用明文配置将会有安全问题,jasypt是一个通用的加解密库,可以使用它。
jasypt默认使用StringEncryptor来进行加解密,也可以自定义自己的加解密类来替换它 。
Jasypt是一个Java库,Java 加密包,用于加密和解密敏感数据,例如密码和API密钥。
它允许开发者以最小的努力为他/她的项目添加基本的加密功能,而且不需要对密码学的工作原理有深刻的了解。
使用Jasypt对密码进行加解密可以保证密码的安全性。
以下是在Spring Boot应用程序中使用Jasypt加密和解密密码的示例代码:
在Spring Boot应用程序的pom.xml文件中添加以下依赖项:
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
在应用程序配置文件(例如application.properties或application.yml)中指定加密和解密密钥。
例如:
jasypt.encryptor.password=mySecretKey
在应用程序中使用Jasypt加密和解密密码非常简单。
您只需要使用@Autowired注释注入org.jasypt.encryption.StringEncryptor bean,
并使用encrypt和decrypt方法加密和解密密码。
例如:
import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MyService {
@Autowired
private StringEncryptor encryptor;
public void doSomething() {
String password = "myPassword";
String encryptedPassword = encryptor.encrypt(password);
String decryptedPassword = encryptor.decrypt(encryptedPassword);
System.out.println("Original password: " + password);
System.out.println("Encrypted password: " + encryptedPassword);
System.out.println("Decrypted password: " + decryptedPassword);
}
}
以下是在Spring Boot中使用Jasypt加解密密码的步骤:
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
jasypt.encryptor.algorithm=PBEWithMD5AndDES
jasypt.encryptor.password=your_secret_password
或者:
jasypt:
encryptor:
algorithm: PBEWithMD5AndDES
password: your_secret_password
import org.jasypt.util.password.StrongPasswordEncryptor;
public class PasswordUtils {
private static final StrongPasswordEncryptor PASSWORD_ENCRYPTOR = new StrongPasswordEncryptor();
public static String encrypt(String password) {
return PASSWORD_ENCRYPTOR.encryptPassword(password);
}
public static boolean checkPassword(String plainPassword, String encryptedPassword) {
return PASSWORD_ENCRYPTOR.checkPassword(plainPassword, encryptedPassword);
}
}
其中,encrypt方法用于加密密码,checkPassword方法用于检查明文密码与密文密码是否匹配。
String encryptedPassword = PasswordUtils.encrypt("password");
userRepository.save(new User("username", encryptedPassword));
spring.datasource.password=ENC(encrypted_password)
或者:
spring:
datasource:
password: ENC(encrypted_password)
其中,encrypted_password是使用Jasypt加密后的密码。
https://www.cnblogs.com/yangzhilong/p/10881589.html
https://www.jianshu.com/p/7bf1b2c01164
https://github.com/ulisesbocchio/jasypt-spring-boot
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。