0

I need to compute the hash string that will match any future hash "within the past hour" starting from now.

I mistakenly did:

now = datetime.now()
hash = now.strftime("%D %H")

but that simply truncates the minutes so if I am at say 4:55, within 5 minutes the "hour" is up.

The past hour is necessary to be part of the hashing since the consumer of the hash string needs to know if the hash was computed within the past hour.

TheOne
  • 10,819
  • 20
  • 81
  • 119
  • 1
    Why does this have to be a hash string? Why not just store the `datetime` object and compare that? – Katriel Mar 01 '12 at 20:10
  • I think you might like [this other question](http://stackoverflow.com/questions/9043172/hash-a-range-of-values) – inspectorG4dget Mar 01 '12 at 20:11
  • @katrielalex, I have a token that is only valid if it was constructed within the past hour. If I provide the datetime object along with the token, an attacker could more easily figure out the hashing algorithm. – TheOne Mar 01 '12 at 20:13
  • @Ramin: if you want your hashes to be cryptographically secure, use a secure hash and you don't have to worry about the attacker breaking the algorithm. If not, you can provide all the information you want. – Katriel Mar 01 '12 at 20:15

2 Answers2

1

I don't think that's possible at all. Take for example the values 4:15, 4:55, 5:30, with hashes X, Y and Z. 4:55 is within the past hour of both 4:55 and 5:30, so Y must be equals to Z. However, 4:15 is withing the past hour of 4:55, but not of 5:30, so X must be equals to Y and different from Z.

Better avoid hashes and do as katrielalex suggested, storing the datetime (or timedelta) and using that in your checks.

Update: Seems I misundestood you, you want hashes for crypto, not for storing things in a hash table for quick access... Maybe if you provide more details of your needs we can help you better, like who will construct the hash, who will check the hash, against what, etc.

There aren't many minutes in an hour, even many seconds, so in principle you could simply hash the initial time (truncated to the nearest minute/second) and, to see if the hash is still valid, take the current time and check the hashes of every minute/second before that. A naïve solution, but can be a starting point for something better.

mgibsonbr
  • 21,755
  • 7
  • 70
  • 112
0

The simple, approximate solution, similar to mgibsonbr's suggestion, would be to generate a new token with the current hour and then if that fails, check again with the past hour.

TheOne
  • 10,819
  • 20
  • 81
  • 119