0

I am trying to write code which validate if given string is hash in one from following types: md4, sha1, sha256. My functions right now looks like:

def hash_is_md5(_hash) -> bool:
    search = re.compile(r"([a-fA-F\d]{32})").search
    return not bool(search(_hash) )

def hash_is_sha1(_hash) -> bool:
    if len(_hash) != 40:
        return False
    try:
        hash_int = int(_hash, 16)
    except ValueError:
        return False
    return True

def hash_is_sha256(_hash) -> bool:
    if (len(_hash.encode("utf-8")) / 8) == 32:
        return True
    else:
        return False

But they doesn't work proper. Any ideas what I coded wrong?

  • *"But they doesn't work proper."* isn't a problem statement. Please indicate exactly what is and isn't working; what you're seeing and how it's different from what you expect. – Jonathon Reinhart Apr 07 '20 at 14:48
  • Also, the only difference between an MD5, SHA-1, and SHA-256 hash is the length of the hex string. That's it; all other information is gone. So why are you using completely different methods for each? – Jonathon Reinhart Apr 07 '20 at 14:50

1 Answers1

0

The output of sha256 is a hash with 64 characters. Dividing it by 8 would actually equal 8. But you don't even need the if statement, you can just check the length of the hash and return that comparison. So the SHA256 function could be

def hash_is_sha256(_hash) -> bool:
    return len(_hash) == 64

The length for sha1 is 40, and for md5 the length is 32, so their functions look like...

def hash_is_sha1(_hash) -> bool:
    return len(_hash) == 40


def hash_is_md5(_hash) -> bool:
    return len(_hash) == 32

All of this assumes that you are taking the hexadecimal hash that is the output of each algorithm. If that assumption is wrong let me know and I can update this.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459