基于SpringBoot的online_music_player_BCrypet加密(登入注册模块_4)

93 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第5天,点击查看活动详情 

BCrypet加密

这里的BCrypet加密方式也是一种安全的不可逆的散列算法加密操作,BCrypet加密和MD5不同之处在于每次对同一个密码加密得到的结果都不相同,也就是在其内部实现了随机加盐处理.这就很好解决了MD5加密的缺点.所以BCrypet加密方式更加安全!并且BCrypet加密可以使加密得到的密文长度最大为60位,而MD5是32位,所以相对于MD5加密,BCrypet破解难度更大!

使用BCrypet加密:

引入依赖:

<!-- security依赖包 (加密)-->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
//BCrypet加密使用演示
package com.example.onlinemusic.tools;
​
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
​
/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: hold on
 * Date: 2022-07-26
 * Time: 23:42
 */
public class BCrypetTest {
    public static void main(String[] args) {
        //模拟从前端获得的密码
        String password = "123456";
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String newPassword = bCryptPasswordEncoder.encode(password);
        System.out.println("加密的密码为: "+newPassword);
        //使用matches方法进行密码的校验
        boolean same_password_result = bCryptPasswordEncoder.matches(password,newPassword);
        //返回true
        System.out.println("加密的密码和正确密码对比结果: "+same_password_result);
        boolean other_password_result = bCryptPasswordEncoder.matches("987654",newPassword);
        //返回false
        System.out.println("加密的密码和错误的密码对比结果: " + other_password_result);
    }
}
​

这里BCrypet加密工具主要通过BCrypetPassWordEncoder对象下的encode加密方法对密码进行加密和matches匹配算法通过密码和加密后的密文进行匹配!

image-20220726234759160

image-20220726234815961

可以看到这里每次加密的结果都不一样,但是都能和正确密码匹配成功!

MD5和BCrypet的异同

  • MD5:一种不加盐的单向hash,不可逆的加密算法,对同一个密码每次hash加密得到的hash值结果都是一样的!所以大多数情况下可以破解!
  • BCrypet:一种加盐的单向Hash,不可逆的加密算法,每次对同一个密码进行加密的结果不同,破解难度更高!

这2个都是目前主流的加密算法,BCrypet更加安全,但是效率低! BCrypet的加盐操作是加入的随机盐,所以每次的加密结果都不一样!

指的注意的是并没有什么密码是绝对安全的,无论那种加密方式都可以被破解的,只是破解的成本和时间问题!如果你的数据并没有价值,那么破解你的密码就毫无意义,也就很安全!