Question

I'm a bit confused that the argument to crypto functions is a string. Should I simply wrap non-string arguments with str() e.g.

hashlib.sha256(str(user_id)+str(expiry_time))
hmac.new(str(random.randbits(256)))

(ignore for the moment that random.randbits() might not be cryptographically good). edit: I realise that the hmac example is silly because I'm not storing the key anywhere!

Was it helpful?

Solution

Well, usually hash-functions (and cryptographic functions generally) work on bytes. The Python strings are basically byte-strings. If you want to compute the hash of some object you have to convert it to a string representation. Just make sure to apply the same operation later if you want to check if the hash is correct. And make sure that your string representation doesn't contain any changing data that you don't want to be checked.

Edit: Due to popular request a short reminder that Python unicode strings don't contain bytes but unicode code points. Each unicode code point contains multiple bytes (2 or 4, depending on how the Python interpreter was compiled). Python strings only contain bytes. So Python strings (type str) are the type most similar to an array of bytes.

OTHER TIPS

You can.

However, for the HMAC, you actually want to store the key somewhere. Without the key, there is no way for you to verify the hash value later. :-)

Oh and Sha256 isn't really an industrial strength cryptographic function (although unfortunately it's used quite commonly on many sites). It's not a real way to protect passwords or other critical data, but more than good enough for generating temporal tokens

Edit: As mentioned Sha256 needs at least some salt. Without salt, Sha256 has a low barrier to being cracked with a dictionary attack (time-wise) and there are plenty of Rainbow tables to use as well. Personally I'd not use anything less than Blowfish for passwords (but that's because I'm paranoid)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top