"Hashlib.HASH" object is not subscribtable

70 Views Asked by At

I'm trying to make a code that takes a word and keeps adding characters until the last 4 of the sha-256 is "ffff".

I've tried using endswith() but I keep getting errors but now i'ts also getting errors. What should I change?

result=""
hash1=str(word)
hash2=""
while True:
  hash1=hash1+"a"
  hash2=hashlib.sha256 (hash1.encode("utf-8"))
  if hash2[-1]!= "c" and_hash2[2]!= "c" and hash2[-3]!= "c" and hash2[-4]!= "c":|
    break
result=hash2
2

There are 2 best solutions below

6
mousetail On

sha256 returns a HASH object, not a string. You can use .hexdigest() to get a hex string, or just .digest() to get a binary string.

You can efficiently find if a binary string would end with some number of digits in hex:

result=""
hash1=str(word)
hash2=""
while True:
  hash1=hash1+"a"
  # add .digest() here
  hash2=hashlib.sha256 (hash1.encode("utf-8")).digest()
  if hash2.endswith(b"\xff\xff")
    break
result=hash2

Try it online!

0
Yurii Motov On

You should use hashlib.sha256(hash1.encode("utf-8")).hexdigest() to get string hash.

result=""
hash1=str(word)
hash2=""
while not hash2.endswith("ffff"):
    hash1=hash1+"a"
    hash2=hashlib.sha256(hash1.encode("utf-8")).hexdigest()
result=hash2