def test_signature_with_salt(self): """signature(value, salt=...) should work""" signer = signing.BytesSigner('predictable-secret', salt='extra-salt') self.assertEqual( signer.signature('hello'), signing.salted_hmac('extra-salt' + 'signer', 'hello', 'predictable-secret').finalize()) self.assertNotEqual( signing.BytesSigner('predictable-secret', salt='one').signature('hello'), signing.BytesSigner('predictable-secret', salt='two').signature('hello'))
def test_signature(self): """signature() method should generate a signature""" signer = signing.BytesSigner('predictable-secret') signer2 = signing.BytesSigner('predictable-secret2') for s in ( b'hello', b'3098247:529:087:', '\u2019'.encode('utf-8'), ): self.assertEqual( signer.signature(s), signing.salted_hmac(signer.salt + 'signer', s, 'predictable-secret').finalize()) self.assertNotEqual(signer.signature(s), signer2.signature(s))
def test_works_with_non_ascii_keys(self): binary_key = b'\xe7' # Set some binary (non-ASCII key) s = signing.BytesSigner(binary_key) self.assertEqual( b'foo\xb5\x8a\xc47\x19\xaeN\xdcMT\x83{PAb\r' b'B\xf3\xd2i\xd1P\x94\xeb^\xc7(\xb4\xd3\x92' b'\xd3\xf4', s.sign('foo'))
def test_unsign_detects_tampering(self): """unsign should raise an exception if the value has been tampered with""" signer = signing.BytesSigner('predictable-secret') value = b'Another string' signed_value = signer.sign(value) transforms = ( lambda s: s.upper(), lambda s: s + b'a', lambda s: b'a' + s[1:], ) self.assertEqual(value, signer.unsign(signed_value)) for transform in transforms: with self.assertRaises(signing.BadSignature): signer.unsign(transform(signed_value))
def test_sign_unsign(self): """sign/unsign should be reversible""" signer = signing.BytesSigner('predictable-secret') examples = [ b'q;wjmbk;wkmb', b'3098247529087', b'3098247:529:087:', b'jkw osanteuh ,rcuh nthu aou oauh ,ud du', b'\u2019', ] for example in examples: signed = signer.sign(example) self.assertIsInstance(signed, bytes) self.assertNotEqual(force_str(example), signed) self.assertEqual(example, signer.unsign(signed))