JAVA实现和PHP兼容的hash_pbkdf2函数

PHP:

使用内置函数:hash_pbkdf2();

PHP代码如下:


JAVA代码如下:

import java.io.*;
import java.net.*;
import java.math.BigInteger;


import javax.crypto.*;
import javax.crypto.spec.*;


static public String hash_pbkdf2(String algorithm, String password, String salt, int iterations, int len) throws Exception {
  PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), iterations, len * 4);
  SecretKeyFactory kFactory = SecretKeyFactory.getInstance(algorithm);
  SecretKey key = kFactory.generateSecret(pbeKeySpec);
  byte[] res = key.getEncoded();
  return toHex(res);
}

private static String toHex(byte[] array){
  BigInteger bi = new BigInteger(1, array);
  String hex = bi.toString(16);
  int paddingLength = (array.length * 2) - hex.length();
  if(paddingLength > 0)
    return String.format("%0" + paddingLength + "d", 0) + hex;
  else
    return hex;
}


hash_pbkdf2(“PBKDF2WithHmacSHA1”, password, salt, 1024, 32);

这时PHP和JAVA输出结果一致