long nonce;
String message = "blahblabahlsdhqwi";
String digest = digest("SHA-256", String + nonce);
byte[] digestBytes = digest.getBytes();
我试图在增加随机数的同时对消息进行哈希处理,直到找到前 4 个字节为 0 的摘要。我怎样才能做到这一点?
long nonce;
String message = "blahblabahlsdhqwi";
String digest = digest("SHA-256", String + nonce);
byte[] digestBytes = digest.getBytes();
我试图在增加随机数的同时对消息进行哈希处理,直到找到前 4 个字节为 0 的摘要。我怎样才能做到这一点?
我花了大约两分半钟才找到:“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()
您可以将 anIntStream
与 a 一起使用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)) {
// ...
}