您可以使用 Spring Security 编写自己的 PasswordEncoder,但首先您需要 AES 加密/解密代码,以下是示例:
public static String encrypt(String value) {
if(value == null){
return value;
}
// SALT is your secret key
Key key = new SecretKeySpec(SALT.getBytes(), "AES");
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
return Base64.encodeBase64String(cipher.doFinal(value.getBytes()));
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
public static String decrypt(String value) {
if(value == null){
return value;
}
// SALT is your secret key
Key key = new SecretKeySpec(SALT.getBytes(), "AES");
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
return new String(cipher.doFinal(Base64.decodeBase64(value)));
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
然后我们可以将这些实用方法与 PasswordEncoder 一起使用,因为您在身份验证时不需要解密用户密码,这不安全,您必须对密码进行编码,然后比较编码的密码。(您必须将用户密码保存在数据库中)这是示例:
公共类 CustomUserPasswordEncoder 实现 PasswordEncoder {
public String encode(CharSequence rawPassword) {
return encrypt(rawPassword.toString());
}
public boolean matches(CharSequence rawPassword, String encodedPassword) {
if (!StringUtils.isBlank(rawPassword) && encode(rawPassword).equals(encodedPassword)) {
return true;
}
return false;
}
}
现在,我们可以像这样设置 Spring Security 密码编码器:
passwordEncoder(new CustomUserPasswordEncoder());