Задать вопрос

Тел: +7 965 3737 888

605

Просмотров

4

Ответов

Sign a string using SHA1, then shrink it using url-safe base65

Sometimes it's useful to sign data to ensure the user does not tamper with it - for example, cookies or hidden form variables. SHA1 is cryptographically secure but weighs in at 40 characters, which is pretty long if you're going to be passing the data around in a URL or a cookie.

These functions knock an SHA1 hash down to just 27 characters, thanks to a base65 encoding that only uses URL-safe characters (defined as characters which are unmodified by Python's urllib.urlencode function). This compressed hash can then be passed around in cookies or URLs, and uncompressed again when the signature needs to be checked.

UPDATE: You probably shouldn't use this; see http://fi.am/entry/urlsafe-base64-encodingdecoding-in-two-lines/ for a smarter approach based on Python's built-in base64 module.

Вопрос полезен? Да0/Нет0
file_2331.py(1.9Кб)
None

Ответы (4):

Ответkcarnold:28.08.2008
Ответ полезен? Да0/Нет0

Might want to make another full snippet, because the approach in the comments doesn't do the sign functionality (sha1 digest).

Ответaarond10ster:27.08.2008
Ответ полезен? Да0/Нет0

Nice snippet! I have one question though.

str(i).lower().replace('L', '')

Whats the point of the replace('L','')? Isn't the string already lowercase by this point?

Ответcarljm:27.08.2008
Ответ полезен? Да0/Нет0

This has another great use: for sites where you want to use an email address as the primary user identifier (no username), one way of generating unique usernames to satisfy Django's User object is to make a hash of the (unique) email address. The problem is that User.username is only 30 chars, not long enough for a 40-character hash. But a 27-character encoding of the hash just fits!

Ответgulopine:27.08.2008
Ответ полезен? Да0/Нет0

I suppose I should do a round of upgrades on django-signedcookies anyway, and this would be a very useful addition.