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

1.4k Views Asked by At
long nonce;
String message = "blahblabahlsdhqwi";
String digest = digest("SHA-256", String + nonce);
byte[] digestBytes = digest.getBytes();

I'm trying to hash through a message whilst incrementing a nonce until I find a digest that has the first 4 bytes that are 0's. How can I do this?

2

There are 2 best solutions below

2
On BEST ANSWER

It took me about two and a half minutes to find: "blahblabahlsdhqwi164370510". I checked it online and that confirmed the hash:

000000007bb0d5ef7b63faaad076fe505a112a485c83ca25af478ea1f81e33d5

My code looks like:

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()
4
On

You could use an IntStream with a limit(n) (to take the first n numbers) and allMatch. Like,

int n = 4;
if (IntStream.range(0, digestBytes.length).limit(n)
        .allMatch(i -> digestBytes[i] == 0)) {
    // ...
}

or just

int n = 4;
if (IntStream.range(0, n).allMatch(i -> digestBytes[i] == 0)) {
    // ...
}