简体   繁体   中英

Comparing two hex values as strings

I'm writing a program that creates random strings and then hashes the string to get its MAC. I want to then look at the first byte for the hash and see if is equal to a specific hex value. (Pre-image attack simplified.) My code successfully pulls the first byte off of each hash but doesn't compare it correctly. So even if the the two bytes are equal, the while loop doesn't recognize it and keeps going indefinitely.

    Random generator = new Random();
    Boolean found = false;
    int i;
    String test="";
    int whatIWant = 169;


    while(found == false)
    {

        String x = "";
        i = 0;

    while(i<15000)
    {   //String x = "";


        int y = generator.nextInt(220)+20;
        x = x + Integer.toHexString(y);
        i++;
    }
    byte[] hexMessage = DatatypeConverter.parseHexBinary(x);
    MessageDigest cript = MessageDigest.getInstance("SHA-512");
    cript.reset();
    cript.update(hexMessage);
    byte[] hash = cript.digest();

    test = String.format("%02X ", hash[0]);

    if(test.equalsIgnoreCase(Integer.toHexString(whatIWant).toString()))
        found = true;

I didn't run your code. I would like to see the result of Integer.toHexString() and I am not sure why you are calling the string returned by Integer.toHexString() to be a string again by .toString() although it is not a big issue since the value should be the same.

All in all I think the outstanding issue may be you never closed your while loop... at least it isn't shown here.

You are searching through bytes ( hash[0] ) for a value (169) greater than the maximum value of a byte (127). That is one reason why your search never finishes. Values > 127 will never be there.

The next problem is that your String conversion pattern "%02X " introduces a space after the hex string. Let's say you search for 127... "7F " will never equal "7F" , so again, your search will never finish, even for byte values within range.

For interest, try adding this to your code:

Outside the loop:

Set<Integer> foundBytes = new TreeSet<Integer>();

At the end of the loop:

if (hash[0] != whatIWant) {
    if (foundBytes.add((int)hash[0])) {
        System.out.printf("[%3d] %s\n", foundBytes.size(), foundBytes);
    }
}

If you set your search value to be greater than 127, you will notice that the foundBytes set quickly fills up with all the possible values of byte after which no more new bytes are found and the print statement is not invoked.

(Your code could be optimized in several ways BTW, but that is not the point of the question.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM