JAVA使用Sha-256加密

1、generateSalt()获取16字节的加密盐

2、hashPassword(String password, String salt) 使用 SHA-256 算法加盐计算哈希值

3、verifyPassword(String inputPassword, String storedHash, String storedSalt)验证密码是否正确

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;


public class Sha256Utils {

    public static String generateSalt() {
        SecureRandom secureRandom = new SecureRandom();
        byte[] salt = new byte[16];  // 16字节盐值
        secureRandom.nextBytes(salt);
        return Base64.getEncoder().encodeToString(salt);  // 返回盐值的Base64编码字符串
    }


    // 使用 SHA-256 算法加盐计算哈希值
    public static String hashPassword(String password, String salt) throws NoSuchAlgorithmException {
        // 拼接密码和盐值
        String passwordWithSalt = password + salt;

        // 使用 SHA-256 计算哈希值
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hashedBytes = digest.digest(passwordWithSalt.getBytes());

        // 返回计算得到的哈希值的Base64编码字符串
        return Base64.getEncoder().encodeToString(hashedBytes);
    }


    // 验证密码是否正确
    public static boolean verifyPassword(String inputPassword, String storedHash, String storedSalt) throws NoSuchAlgorithmException {
        // 使用相同的盐值计算输入密码的哈希值
        String hashOfInput = hashPassword(inputPassword, storedSalt);

        // 比较计算出的哈希值与存储的哈希值
        return hashOfInput.equals(storedHash);
    }



    public static void main(String[] args) throws NoSuchAlgorithmException {
        // 模拟用户注册
        String password = "password";

        // 生成盐值
        String salt = generateSalt();
        System.out.println("Salt: " + salt);

        // 计算密码的哈希值
        String hash = hashPassword(password, salt);
        System.out.println("Password Hash: " + hash);

        // 模拟用户登录验证
        String inputPassword = "password";  // 用户输入的密码
        boolean isPasswordCorrect = verifyPassword(inputPassword, hash, salt);
        System.out.println("Password verification result: " + isPasswordCorrect);
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值