【发布时间】:2016-06-25 17:03:06
【问题描述】:
我之前在 Python 中编写了一个使用 PBKDF2 对目标字符串进行乱码的函数:
from hashlib import pbkdf2_hmac
from binascii import hexlify
def garbleString(string, salt, iterations, hash_algorithm):
target = str.encode(string)
dk = pbkdf2_hmac(hash_algorithm, target, salt, iterations)
hash = hexlify(dk)
return (hash, salt, iterations)
>>> garbleString("1000000000","salt",100000,'sha256')
('d973f4855206bd777b25355782f1b14bf06fb395bf49a26086035b3b8820a74b', 'salt', 100000)
根据这个页面,这个函数是正确的——它为相同的输入产生相同的哈希值。 http://www.neurotechnics.com/tools/pbkdf2
我现在正在尝试在 Java 中实现相同的功能,这就是我现在的位置:
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.xml.bind.DatatypeConverter;
public class GarbledStringFactory {
private String algorithm;
public GarbledStringFactory(String algorithm){
this.algorithm = algorithm;
}
public String getGarbledString(String string, String salt, int iterations, int derivedKeyLength) throws NoSuchAlgorithmException, InvalidKeySpecException {
SecretKeyFactory f = SecretKeyFactory.getInstance(this.algorithm);
KeySpec spec = new PBEKeySpec(string.toCharArray(), salt.getBytes(), iterations, derivedKeyLength * 8);
SecretKey key = f.generateSecret(spec);
String hexStr = DatatypeConverter.printHexBinary(key.getEncoded());
return hexStr;
}
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
// TODO Auto-generated method stub
GarbledStringFactory factory = new GarbledStringFactory("PBKDF2WithHmacSHA256");
String hash = factory.getGarbledString("1000000000","salt",100000,32);
System.out.println(hash);
}
}
这会产生哈希“D973F4855206BD777B25355782F1B14BF06FB395BF49A26086035B3B8820A74B”,它是相同的,只是字母大小写不同。外壳重要吗?
【问题讨论】:
标签: java python hash cryptography pbkdf2