Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/397.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在Python中使用本机库(即hashlib),使用byte[]作为输入,而不是十六进制字符串来迭代sha256_Java_Python_Hash_Hex_Sha256 - Fatal编程技术网

Java 如何在Python中使用本机库(即hashlib),使用byte[]作为输入,而不是十六进制字符串来迭代sha256

Java 如何在Python中使用本机库(即hashlib),使用byte[]作为输入,而不是十六进制字符串来迭代sha256,java,python,hash,hex,sha256,Java,Python,Hash,Hex,Sha256,背景:我有一个迭代哈希算法,需要从Python脚本和JavaWeb应用程序计算 Psuedo代码: hash = sha256(raw) for x=1 to 64000 hash = sha256(hash) 其中,哈希是长度为32的字节数组,而不是长度为64的十六进制字符串 我希望将其保留为字节的原因是,尽管Python可以在每次迭代之间转换为十六进制字符串,并将处理时间保持在1秒以下,但Java需要3秒的字符串开销 因此,Java代码如下所示: // hash one time... b

背景:我有一个迭代哈希算法,需要从Python脚本和JavaWeb应用程序计算

Psuedo代码:

hash = sha256(raw)
for x=1 to 64000 hash = sha256(hash)
其中,哈希是长度为32的字节数组,而不是长度为64的十六进制字符串

我希望将其保留为字节的原因是,尽管Python可以在每次迭代之间转换为十六进制字符串,并将处理时间保持在1秒以下,但Java需要3秒的字符串开销

因此,Java代码如下所示:

// hash one time...
byte[] result = sha256(raw.getBytes("UTF-8"));

// then hash 64k-1 more times
for (int x = 0; x < 64000-1; x++) {
  result = sha256(result);
}

// hex encode and print result
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
for (int i=0; i<buf.length; i++) {
  formatter.format("%02x", buf[i]);
}
System.out.println(sb.toString());
import hashlib

# hash 1 time...
hasher = hashlib.sha256()
hasher.update(raw)
digest = hasher.digest()

# then hash 64k-1 times
for x in range (0, 64000-1):
  # expect digest is bytes and not hex string
  hasher.update(digest) 
  digest = hasher.digest()
print digest.encode("hex")

Python结果计算第一个摘要(字符串)的十六进制表示形式的哈希值,而不是原始摘要字节。所以,我得到了不同的输出。

方法。hasher的更新将参数附加到前面的文本()。相反,您应该在每次需要计算摘要时创建新的哈希器

import hashlib

# hash 1 time...
digest = hashlib.sha256(raw).digest()

# then hash 64k-1 times
for x in range(0, 64000-1):
  digest = hashlib.sha256(digest).digest()
print digest.encode("hex")

谢谢Michal解决了这个问题。我在代码中添加了一行,以获得一个新的hasher:hasher=hashlib.sha256(),作为for循环中的第一行。让我感到困惑的是,Java在调用摘要后重置散列输入,而Python没有。。。。现在我看到你用更少的代码做了同样的事情。再次感谢。