Spring Security实现密码加密详解

Spring Security实现密码加密方法

首先,Spring Security提供了强大的加密工具PasswordEncoder,PasswordEncoder接口的代码如下:

public interface PasswordEncoder {
    String encode(CharSequence var1);

    boolean matches(CharSequence var1, String var2);

    default boolean upgradeEncoding(String encodedPassword) {
        return false;
    }
}

该接口下定义了三个方法,encode是对加密加密方法,而Boolean类型的match方法是用来验证密码和加密后密码是否一致的如果一致则返回true。和authentication.encoding包中的PasswordEncoder接口相比,详细的可以到authentication.encoding包下查找相应的代码,这里就不列举了。

然后,Spring Security提供了BCryptPasswordEncoder类,该类实现了Spring的PasswordEncoder接口,使用BCrypt强哈希方法来对密码进行加密,通过BCrypt强哈希方法每一次加密的结果都不一样,我们可以看看BCryptPasswordEncoder的源码:

public class BCryptPasswordEncoder implements PasswordEncoder {
    private Pattern BCRYPT_PATTERN;
    private final Log logger;
    private final int strength;
    private final SecureRandom random;

    public BCryptPasswordEncoder() {
        this(-1);
    }

    public BCryptPasswordEncoder(int strength) {
        this(strength, (SecureRandom)null);
    }

    public BCryptPasswordEncoder(int strength, SecureRandom random) {
        this.BCRYPT_PATTERN = Pattern.compile("\\A\\$2a?\\$\\d\\d\\$[./0-9A-Za-z]{53}");
        this.logger = LogFactory.getLog(this.getClass());
        if (strength == -1 || strength >= 4 && strength <= 31) {
            this.strength = strength;
            this.random = random;
        } else {
            throw new IllegalArgumentException("Bad strength");
        }
    }

    public String encode(CharSequence rawPassword) {
        String salt;
        if (this.strength > 0) {
            if (this.random != null) {
                salt = BCrypt.gensalt(this.strength, this.random);
            } else {
                salt = BCrypt.gensalt(this.strength);
            }
        } else {
            salt = BCrypt.gensalt();
        }

        return BCrypt.hashpw(rawPassword.toString(), salt);
    }

    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        if (encodedPassword != null && encodedPassword.length() != 0) {
            if (!this.BCRYPT_PATTERN.matcher(encodedPassword).matches()) {
                this.logger.warn("Encoded password does not look like BCrypt");
                return false;
            } else {
                return BCrypt.checkpw(rawPassword.toString(), encodedPassword);
            }
        } else {
            this.logger.warn("Empty encoded password");
            return false;
        }
    }
}

毫无疑问,BCryptPasswordEncoder类实现了PasswordEncoder 接口下方法,实现了方法encode,方法encode采用强哈希的BCrypt方式进行加密。

应用,我们在编写用户实体类的时候,可能会对密码password进行加密,这时候我们就可以编写一个加密的方法,例如:

public void setEncodePassword(String password){
        //PasswordEncoder是一个接口,而BCryptPasswordEncoder实现了这个接口,里面有一个encode方法是对面进行加密
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodePWD =encoder.encode(password); //加密完之后赋值给encodePWD
        this.password = encodePWD;
    }

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Security本身并不提供DESede加密算法的实现,但你可以使用Java的标准库来实现。下面是一个示例代码,演示了如何在Spring Security中使用DESede进行加密。 首先,你需要创建一个自定义的PasswordEncoder类来实现加密和解密方法。你可以使用`javax.crypto`包中的`Cipher`类来执行加密和解密操作。下面是一个简单的示例: ```java import org.springframework.security.crypto.password.PasswordEncoder; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESedeKeySpec; import java.security.spec.KeySpec; import java.util.Base64; public class MyPasswordEncoder implements PasswordEncoder { private static final String ENCRYPTION_ALGORITHM = "DESede"; private static final String SECRET_KEY = "your_secret_key"; // 自定义的密钥 @Override public String encode(CharSequence rawPassword) { try { Cipher cipher = getCipher(Cipher.ENCRYPT_MODE); byte[] encryptedBytes = cipher.doFinal(rawPassword.toString().getBytes()); return Base64.getEncoder().encodeToString(encryptedBytes); } catch (Exception e) { throw new RuntimeException("Error occurred while encoding password", e); } } @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { try { Cipher cipher = getCipher(Cipher.DECRYPT_MODE); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encodedPassword)); String decryptedPassword = new String(decryptedBytes); return rawPassword.toString().equals(decryptedPassword); } catch (Exception e) { throw new RuntimeException("Error occurred while decoding password", e); } } private Cipher getCipher(int cipherMode) throws Exception { KeySpec keySpec = new DESedeKeySpec(SECRET_KEY.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ENCRYPTION_ALGORITHM); SecretKey key = keyFactory.generateSecret(keySpec); Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM); cipher.init(cipherMode, key); return cipher; } } ``` 然后在Spring Security的配置类中,将自定义的PasswordEncoder实例注入到AuthenticationManagerBuilder中: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private MyPasswordEncoder passwordEncoder; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .passwordEncoder(passwordEncoder) .withUser("user") .password("your_encrypted_password") // 加密后的密码 .roles("USER"); } // 其他配置... } ``` 这样,你就可以在Spring Security中使用自定义的DESede加密算法来加密和验证密码了。请注意,为了安全起见,你应该将密钥存储在安全的地方,并且不要直接将明文密码存储在代码中。此示例仅用于演示目的,实际应用中请根据具体需求进行安全处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值