def _pack_code(cls, data): payload = json.dumps(data).encode() code = crypto.encrypt( payload, context='desecapi.serializers.AuthenticatedActionSerializer' ).decode() return code.rstrip('=')
def test_encrypt_decrypt_raises_on_tampering(self): ciphertext = crypto.encrypt(b'test', context=self.context) with self.assertRaises(ValueError): ciphertext_decoded = ciphertext.decode() ciphertext_tampered = (ciphertext_decoded[:30] + 'TAMPERBEEF' + ciphertext_decoded[40:]).encode() crypto.decrypt(ciphertext_tampered, context=self.context) with self.assertRaises(ValueError): crypto.decrypt(ciphertext, context=f'{self.context}2')
def test_encrypt_has_high_entropy(self): def entropy(value: str): result = 0 counts = [value.count(char) for char in set(value)] for count in counts: count /= len(value) result -= count * log(count, 2) return result * len(value) ciphertext = crypto.encrypt(b'test', context=self.context) self.assertGreater(entropy(ciphertext), 100) # arbitrary
def test_encrypt_decrypt(self): plain = b'test' ciphertext = crypto.encrypt(plain, context=self.context) self.assertEqual(plain, crypto.decrypt(ciphertext, context=self.context))
def _pack_code(cls, data): payload = json.dumps(data).encode() payload_enc = crypto.encrypt(payload, context='desecapi.serializers.AuthenticatedActionSerializer') return urlsafe_b64encode(payload_enc).decode()