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

时间:2017-05-20 15:32:27

标签: java cryptography string-hashing

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

我正在尝试在递增nonce时通过消息进行散列,直到找到具有前4个字节为0的摘要。我怎么能这样做?

2 个答案:

答案 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)) {
    // ...
}