Java实现密码加密实现步骤【bcrypt算法】

一、SpringBoot和SSM框架均可实现密码加密的方法

在Spring Boot和SSM中实现密码加密可以使用bcrypt算法。bcrypt是一种密码哈希函数,通过将密码与随机生成的盐值进行混合,然后再进行多次迭代的计算,最终生成一个安全的哈希密码。

下面是使用bcrypt算法实现密码加密的步骤和代码示例:

1.在pom.xml文件中添加Spring Security依赖。

XML 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2.创建一个配置类来配置Spring Security。

java 复制代码
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
            .anyRequest().authenticated()
            .and()
            .formLogin().permitAll()
            .and()
            .logout().permitAll();
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        // 返回自定义的UserDetailsService实现类,用于从数据库中获取用户信息
        return new UserDetailsServiceImpl();
    }
}

3.创建自定义的UserDetailsService实现类:实现UserDetailsService接口,用于从数据库中获取用户信息。

java 复制代码
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("User not found");
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), getAuthorities(user));
    }

    private Collection<GrantedAuthority> getAuthorities(User user) {
        List<String> roles = user.getRoles();
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String role : roles) {
            authorities.add(new SimpleGrantedAuthority(role));
        }
        return authorities;
    }
}

4.实现密码加密:在注册或更新密码时,使用BCryptPasswordEncoder类的encode()方法进行密码加密。

java 复制代码
@Autowired
private BCryptPasswordEncoder passwordEncoder;

public void registerUser(User user) {
    // 加密密码
    String encryptedPassword = passwordEncoder.encode(user.getPassword());
    user.setPassword(encryptedPassword);
    // 保存到数据库
    userMapper.save(user);
}

总结

通过以上步骤,我们可以在Spring Boot和SSM中实现密码加密。使用bcrypt算法可以保障密码的安全性,并且减少了手动编写哈希函数的工作量。

相关推荐
折哥的程序人生 · 物流技术专研8 小时前
第4篇:Lambda 简化策略模式(Java 8+)
java·设计模式·策略模式·函数式编程·lambda·代码简化·扩充系列
researcher-Jiang8 小时前
高性能计算之OpenMP——超算习堂学习1
android·java·学习
西门吹-禅10 小时前
java springboot N+1问题
java·开发语言·spring boot
DLYSB_10 小时前
生命通道:如何用 HIS 医疗系统直连网络声光终端,打造“零延误”的危急值响应网关?
java·网络·数据库·报警灯
skywalk816310 小时前
设计并实现段言的 C FFI 绑定机制 @Trae
c语言·开发语言·python·编程
weixin_BYSJ198711 小时前
SpringBoot + MySQL 乒乓球运动员信息管理系统项目实战--附源码04954
java·javascript·spring boot·python·django·flask·php
AI小码11 小时前
LLM 应用的缓存工程:当每次 API 调用都在燃烧成本
java·人工智能·spring·计算机·llm·编程·api
Hui Baby11 小时前
Spring Security
java·后端·spring
IT笔记12 小时前
【Rust】Rust Match 模式匹配详解
java·开发语言·rust
2zcode12 小时前
免费开源项目文档:基于MATLAB卷积神经网络的口罩佩戴检测系统
开发语言·matlab·cnn