Esempio n. 1
0
    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')
Esempio n. 2
0
 def _unpack_code(cls, code, *, ttl):
     try:
         payload_enc = urlsafe_b64decode(code.encode())
         payload = crypto.decrypt(payload_enc, context='desecapi.serializers.AuthenticatedActionSerializer', ttl=ttl)
         return json.loads(payload.decode())
     except (TypeError, UnicodeDecodeError, UnicodeEncodeError, json.JSONDecodeError, binascii.Error):
         raise ValueError
Esempio n. 3
0
 def _unpack_code(cls, code):
     try:
         payload_enc = urlsafe_b64decode(code.encode())
         payload = crypto.decrypt(payload_enc, context='desecapi.serializers.AuthenticatedActionSerializer',
                                  ttl=settings.VALIDITY_PERIOD_VERIFICATION_SIGNATURE.total_seconds())
         return json.loads(payload.decode())
     except (TypeError, UnicodeDecodeError, UnicodeEncodeError, json.JSONDecodeError, binascii.Error):
         raise ValueError
Esempio n. 4
0
 def _unpack_code(cls, code, *, ttl, _retry=True):
     code += -len(code) % 4 * '='
     try:
         payload = crypto.decrypt(
             code.encode(),
             context='desecapi.serializers.AuthenticatedActionSerializer',
             ttl=ttl)
         return json.loads(payload.decode())
     except ValueError:  # TODO remove this once all urlsafe_b64encode'd codes have expired (~30d after deployment)
         if _retry:
             return cls._unpack_code(urlsafe_b64decode(
                 code.encode()).decode(),
                                     ttl=ttl,
                                     _retry=False)
         else:
             raise
     except (TypeError, UnicodeDecodeError, UnicodeEncodeError,
             json.JSONDecodeError, binascii.Error):
         raise ValueError
Esempio n. 5
0
 def test_encrypt_decrypt(self):
     plain = b'test'
     ciphertext = crypto.encrypt(plain, context=self.context)
     self.assertEqual(plain, crypto.decrypt(ciphertext,
                                            context=self.context))