0

i have a given string, let's say 'test123' i calculate the sha1 hash value of the string with and take the first 5 characters:

sha1(teststring.encode("utf-8")).hexdigest()[:5]

now i want to generate a random string that has the same first 5 sha1 hash characters

''.join(random.choice(string.ascii_letters + string.digits + string.punctuation) for _ in range(16))

i have a working solution were i just generate random strings and hash them until i find a matching one.

is there a faster way to achive this?

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
dOPELELE
  • 33
  • 1
  • 6
  • 1
    think that this related question will help you: https://stackoverflow.com/questions/3859100/convert-sha1-back-to-string – Yossi Levi Oct 24 '20 at 15:17
  • [random.choices](https://docs.python.org/3.8/library/random.html#random.choices) should be a bit faster than repeated calls to random.choice. – Wups Oct 24 '20 at 15:23
  • `hexdigest()` does not give you bits, it gives you a string, where each letter represents a hex values ("0" through "F" to mean numerical 0 through 15). So if you slice off the first five of those, you now have five letters, representing 20 bits. – Mike 'Pomax' Kamermans Oct 24 '20 at 15:44
  • You could utilize the fact, that a small change to the string will result in a completely different hash. So you don't need to create a new random string each time. – Wups Oct 24 '20 at 16:02

1 Answers1

0

No there isn't anything beside brute force.

SHA-1 is a cryptographic hash function, and your question is very close to the matter of finding collisions.

Finding a faster way than brute force would defeat the purpose of SHA-1. Have a look at the wikipedia article, it's pretty well documented.

dader
  • 1,304
  • 1
  • 12
  • 31