【问题标题】:Authentification with salt使用盐进行身份验证
【发布时间】:2019-06-01 13:03:19
【问题描述】:

我正在尝试编写登录活动,我在下面编写了hashPassword 函数。为什么相同的盐和密码会给出不同的结果?

  import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.PBEKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

public class Main {

    public static void main(String[] args) {


        System.out.println("Hello World!");
       try { System.out.println("test1: "+hashPassword("[B@2b1e4124","bfnfnfjfjf"));
           System.out.println("test2: "+hashPassword("[B@2b1e4124","bfnfnfjfjf"));}
       catch (NoSuchAlgorithmException | InvalidKeySpecException e){}

    }
     public static  String hashPassword(String password, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException {

        char[] passwordChars = password.toCharArray();
        byte[] saltBytes =salt.getBytes();
        PBEKeySpec spec = new PBEKeySpec(
                passwordChars,
                saltBytes,
                5000,
                10
        );
        SecretKeyFactory key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
        byte[] hashedPassword = key.generateSecret(spec).getEncoded();
        return hashedPassword.toString();
    }

}

【问题讨论】:

    标签: java authentication salt sha


    【解决方案1】:

    您的哈希实际上每次都计算相同的结果,但您在结果字节数组上调用toString。这会返回一个调试字符串,每个实例都不同(详见this question)。

    代替

    return hashedPassword.toString();
    

    你应该

    return hashedPassword;
    

    ...直接使用byte[]

    如果您想以人类可读的格式显示哈希,可以这样打印:

    String hashString = new BigInteger(1, hashedPassword).toString(16);
    System.out.println(hashString);
    

    您的代码中有第二个错误。 PBEKeySpec 构造函数的第四个参数是以bits 为单位的长度。 10 太短了,没用。您可能想要 512(SHA512 输出长度)。

    【讨论】:

      猜你喜欢
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 2011-05-08
      • 2017-04-17
      • 2017-06-13
      • 2017-03-11
      • 2013-05-30
      • 2015-09-23
      相关资源
      最近更新 更多