[英]Java 8 vs Python 2.7 pbkdf2 hashing — different output hash letter casing
我以前用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”,該值相同,只是字母大小寫不同。 機殼重要嗎?
不,機殼沒關系。
如果檢查散列,會發現其中包含的唯一字母是從A到F。這實際上不是一個字符串,而是一個十六進制(以16為底)的數字,等效於98356763175438224738455306401383784358747884932932620687880657531803811513935691,十進制/以10為底。
數字是大寫還是小寫都無所謂。 意思是一樣的。
您可以在Python解釋器中看到這一點,其中前導0x
表示一個十六進制數:
>>> hex(12)
'0xc'
>>> 0xf
15
>>> 0xF
15
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.