long nonce;
String message = "blahblabahlsdhqwi";
String digest = digest("SHA-256", String + nonce);
byte[] digestBytes = digest.getBytes();
我正在尝试在递增nonce时通过消息进行散列,直到找到具有前4个字节为0的摘要。我怎么能这样做?
答案 0 :(得分:2)
我花了大约两分半钟才找到:“blahblabahlsdhqwi164370510”。我在网上查了一下,确认了哈希:
000000007bb0d5ef7b63faaad076fe505a112a485c83ca25af478ea1f81e33d5
我的代码如下:
public static void main(String[] args) throws UnsupportedEncodingException {
// I use Bouncy Castle.
SHA256Digest SHA = new SHA256Digest();
byte[] digest = new byte[32];
byte[] textBytes;
long nonce = 0L;
String message = "blahblabahlsdhqwi";
boolean found;
do {
// Calculate digest.
textBytes = (message + nonce).getBytes("UTF-8");
SHA.update(textBytes, 0, textBytes.length);
SHA.doFinal(digest, 0);
// Check for 4 zeros.
found = digest[0] == 0 && digest[1] == 0 && digest[2] == 0 && digest[3] == 0;
// Try next nonce.
++nonce;
} while (!found);
System.out.println("Found at: SHA256(" + message + (nonce - 1L) +")");
System.out.println("SHA256 digest = " + Arrays.toString(digest));
} // end main()
答案 1 :(得分:1)
您可以IntStream
使用limit(n)
(以获取前n
个数字)和allMatch
。像,
int n = 4;
if (IntStream.range(0, digestBytes.length).limit(n)
.allMatch(i -> digestBytes[i] == 0)) {
// ...
}
或只是
int n = 4;
if (IntStream.range(0, n).allMatch(i -> digestBytes[i] == 0)) {
// ...
}