如何检查字符串的前 n 个字节是否为零?

How to check if the first n bytes of a string are zeroes?

long nonce;
String message = "blahblabahlsdhqwi";
String digest = digest("SHA-256", String + nonce);
byte[] digestBytes = digest.getBytes();

我正在尝试对一条消息进行哈希处理,同时递增一个随机数,直到找到前 4 个字节为 0 的摘要。我该怎么做?

您可以使用 IntStreamlimit(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)) {
    // ...
}

我花了大约两分半钟才找到:"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()