views:

158

answers:

3

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!

+1  A: 

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. :-)

Chris Jester-Young
+6  A: 

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.

unbeknown
You might want to clarify the difference between 'str' and 'unicode', both Python string types.
Nick Johnson
A: 

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)

Robert Gould
Do you really mean that? Of course, if you want to use it to protect passwords, you should add a salt, but that is true for all hash functions. Personally, I would say that SHA-256 is as industrial strength as hash functions come.
Rasmus Faber
As you mention, 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)
Robert Gould