Created
August 22, 2014 07:10
-
-
Save adoc/a3bf61d5014d9e096367 to your computer and use it in GitHub Desktop.
py_hmac_validator: Formencode Hmac Validator.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HmacValidator(formencode.validators.FancyValidator): | |
""" | |
""" | |
hashalg = hashlib.sha512 | |
messages = { | |
'malformed': 'Malformed challenge hash.' | |
} | |
def __init__(self, key, *args, **kwa): | |
for k in ('hashalg', ): | |
if k in kwa: | |
setattr(self, k, kwa.pop(k)) | |
self.key = key | |
self.digest_size = self.hashalg().digest_size | |
formencode.validators.FancyValidator.__init__(self, *args, **kwa) | |
def _convert_to_python(self, value, state): | |
value = base64.urlsafe_b64decode(value) | |
return value[:self.digest_size], value[self.digest_size:] | |
def _convert_from_python(self, value, state): | |
alg = hmac.new(self.key, msg=value, digestmod=self.hashalg) | |
return base64.urlsafe_b64encode(alg.digest() + value) | |
def _validate_python(self, value, state): | |
challenge_digest, value = value | |
alg = hmac.new(self.key, msg=value, digestmod=self.hashalg) | |
digest = alg.digest() | |
if len(challenge_digest) < self.digest_size: | |
raise formencode.Invalid(self.message('malformed', state), value, | |
state) | |
if not hmac.compare_digest(digest, challenge_digest) is True: | |
raise formencode.Invalid(self.message('malformed', state), value, | |
state) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment