JAVA实现和PHP兼容的hash_pbkdf2函数

PHP:

使用内置函数:hash_pbkdf2();

比如:

$data = hash_pbkdf2 ('sha1', $password , $salt , 1024, 32, false);




JAVA:

mport 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输出结果一致



你可能感兴趣的:(JAVA实现和PHP兼容的hash_pbkdf2函数)