Adding a check of string type for hmacs

- To ensure comparison is done on binary data

The method would first check if the 2 hmacs are a python
`six.stringtype`. If they are, they would be encoded using
'utf-8' as the encoding scheme to binary data.

Change-Id: Idf59f669087a39c30eee4e533899b95ede66e198
This commit is contained in:
Rahul Nair 2017-02-15 14:33:48 -06:00 committed by rahulunair
parent d74b933801
commit f1d332a01d
2 changed files with 8 additions and 0 deletions

View File

@ -14,6 +14,8 @@
import hmac
import six
try:
constant_time_compare = hmac.compare_digest
@ -27,6 +29,10 @@ except AttributeError:
content-based short circuiting behaviour, making it appropriate
for cryptography.
"""
if isinstance(first, six.string_types):
first = first.encode('utf-8')
if isinstance(second, six.string_types):
second = second.encode('utf-8')
if len(first) != len(second):
return False
result = 0

View File

@ -34,6 +34,7 @@ class SecretUtilsTest(testscenarios.TestWithScenarios,
self.converter(u'abcd')))
self.assertTrue(ctc(self.converter(u''),
self.converter(u'')))
self.assertTrue(ctc('abcd', 'abcd'))
self.assertFalse(ctc(self.converter(u'abcd'),
self.converter(u'efgh')))
self.assertFalse(ctc(self.converter(u'abc'),
@ -50,3 +51,4 @@ class SecretUtilsTest(testscenarios.TestWithScenarios,
self.converter(u'a')))
self.assertFalse(ctc(self.converter(u'abcd1234'),
self.converter(u'1234abcd')))
self.assertFalse(ctc('abcd1234', '1234abcd'))