Java 迭代 SHA-1 哈希与 Python

Java iterative SHA-1 hashing vs Python

我在 Java 中有一个关于散列算法的具体问题。 我有 2 个客户,一个 运行 python 和另一个 运行 Java (我知道,我可以只使用 python 解决所有问题,但现在我几乎需要才能使用java).

客户端需要以相同的方式比较插入的密码(即:如果 PIN 在 java 客户端上生成哈希 ,则需要相同的 哈希由 python 客户端生成。

我在这里阅读:

并在这里研究了官方文档: https://docs.oracle.com/javase/7/docs/api/java/security/MessageDigest.html

并发现 python 允许无缝迭代编码,而 java 则不允许。我尝试通过以下方式使用 .clone() 方法解决问题(java 代码):

        // creation of SHA-1 instance:
        MessageDigest message = MessageDigest.getInstance("SHA-1");
        // construction of the string to hash:
        String secretMessage = "0" + myPassWord + mySalt;
        // updating the instance:
        message.update(secretMessage.getBytes());
        // cloning the instance:
        MessageDigest messageClone = (MessageDigest) message.clone();
        // digesting the clone: the result is of type byte[]:
        byteResult = messageClone.digest();
        // construction of the previousHash: this will be used in the 
        // next run of SHA-1 hashing. Python runs everything in lowercase.
        // the hash is rendered as HEX characters String:
        prevHash = (DatatypeConverter.printHexBinary(byteResult)).toLowerCase();
        secretMessage = prevHash + "1" + myPassWord + mySalt;
        message.update(secretMessage.getBytes());
        // compute the final digest:
        byteResult = message.digest();
        // print it:
        System.out.println(DatatypeConverter.printHexBinary(byteResult));

现在,通过在第一次迭代(索引“0”)上执行 System.out.println,哈希重合。

不幸的是,随后的索引出了点问题,看在我的份上,我无法理解它是什么。我怀疑这与 python 如何转换字符串并将其插入 secretMessage 变量有关。

为了您的信息,这里是 python 中的代码:

digest2 = ""
for i in range (0, 2):
    digest2 = sha1(digest2 + str(i) + password_to_hash + salt).hexdigest()
    print digest2

问题在于,在 Java 实现中,您首先向 MessageDigest 提供迭代字符串,然后在不重置 MessageDigest 的情况下向 MessageDigest 提供第二次迭代字符串,因此实际上它正在创建 String 的单个散列,例如:

"0" + pw + salt + sha-of-data-so-far + "1" + pw + salt

然而,python 实现为第二次迭代启动了一个新散列并创建了两个散列:

"0" + pw + salt

然后:

sha-of-iteration-1 + "1" + pw + salt