Permalink
Browse files

Use hmac module for signing messages, which is more secure than sha1 …

…directly against concatenated strings - thanks Armin Ronacher for the tip
  • Loading branch information...
1 parent cd6d304 commit 3515a762ecce7c4db0e33565b0c7893e942f4cb5 Simon Willison committed Sep 24, 2009
Showing with 7 additions and 6 deletions.
  1. +5 −4 django_openid/signed.py
  2. +2 −2 django_openid/tests/signing_tests.py
@@ -37,6 +37,7 @@
import pickle, base64
from django.conf import settings
from django.utils.hashcompat import sha_constructor
+import hmac
def dumps(obj, secret = None, compress = False, extra_salt = ''):
"""
@@ -99,7 +100,7 @@ def sign(value, key = None):
'sign() needs bytestring, not unicode: %s' % repr(value)
if key is None:
key = settings.SECRET_KEY
- return value + '.' + base64_sha1(value + key)
+ return value + '.' + base64_hmac(value, key)
def unsign(signed_value, key = None):
if isinstance(signed_value, unicode):
@@ -109,10 +110,10 @@ def unsign(signed_value, key = None):
if not '.' in signed_value:
raise BadSignature, 'Missing sig (no . found in value)'
value, sig = signed_value.rsplit('.', 1)
- if base64_sha1(value + key) == sig:
+ if base64_hmac(value, key) == sig:
return value
else:
raise BadSignature, 'Signature failed: %s' % sig
-def base64_sha1(s):
- return encode(sha_constructor(s).digest())
+def base64_hmac(value, key):
+ return encode(hmac.new(key, value, sha_constructor).digest())
@@ -15,11 +15,11 @@ def test_sign_uses_correct_key(self):
s = 'This is a string'
self.assertEqual(
signed.sign(s),
- s + '.' + signed.base64_sha1(s + settings.SECRET_KEY)
+ s + '.' + signed.base64_hmac(s, settings.SECRET_KEY)
)
self.assertEqual(
signed.sign(s, 'sekrit'),
- s + '.' + signed.base64_sha1(s + 'sekrit')
+ s + '.' + signed.base64_hmac(s, 'sekrit')
)
def sign_is_reversible(self):

0 comments on commit 3515a76

Please sign in to comment.