hongjli
2025-04-15 1acf9a48021d0af1d81fdf3ed8fcf8dffd020f6b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.weiwojc.utils;
 
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.security.crypto.bcrypt.BCrypt;
 
public class PasswordUtils {
    
    /**
     * 生成随机盐值
     */
    public static String generateSalt() {
        return BCrypt.gensalt();
    }
 
    /**
     * 使用盐值加密密码
     */
    public static String hashPassword(String password, String salt) {
        return BCrypt.hashpw(password, salt);
    }
 
    /**
     * 验证密码
     */
    public static boolean verifyPassword(String password, String hashedPassword) {
        return BCrypt.checkpw(password, hashedPassword);
    }
 
    /**
     * 从BCrypt哈希值中提取盐值
     */
    public static String extractSaltFromHash(String hashedPassword) {
        // BCrypt哈希的前29个字符就是盐值
        return hashedPassword.substring(0, 29);
    }