我使用Spring Boot创建应用程序并需要加密功能。
我选择使用Spring Security进行加密,但我面临的困境应该采用哪种方式?
使用静态方法将加密创建为最终的util类。我更喜欢这种方式,但它们是一个问题,我需要从application.properties
注入salt属性public final class EncryptionUtil {
@Value("${encryption.salt}") // can't inject value from application.properties, because static property
private static String salt;
@Value("${encryption.password}") // can't inject value from application.properties, because static property
private static String password;
public static byte[] encrypt(String text) throws UnsupportedEncodingException {
BytesEncryptor encryptor = Encryptors.standard(password, salt);
return encryptor.encrypt(text.getBytes("UTF-8"));
}
public static String decrypt(byte[] bytes) {
BytesEncryptor encryptor = Encryptors.standard(password, salt);
return new String(encryptor.decrypt(bytes));
}
}
使用@Service / @ Component注释创建服务/组件,然后使用application.properties中的@Value注入salt属性,然后使用@Autowired调用
@Service
public class EncryptionService {
@Value("${encryption.salt}")
private String salt;
@Value("${encryption.password}")
private String password;
public byte[] encrypt(String text) throws UnsupportedEncodingException {
BytesEncryptor encryptor = Encryptors.standard(password, salt);
return encryptor.encrypt(text.getBytes("UTF-8"));
}
public String decrypt(byte[] bytes) {
BytesEncryptor encryptor = Encryptors.standard(password, salt);
return new String(encryptor.decrypt(bytes));
}
}