def __init__(self, user_id, user_ik): super().__init__(user_id) if user_ik is None: raise ValueError('User ik must be set') self.encryption = JWEDirEncrypter() self.decryption = JWEDirDecrypter() self.user_ik = user_ik
def test_decryption(self): cek = os.urandom(32) plain_text = "test decryption" encrypter = JWEDirEncrypter() decrypter = JWEDirDecrypter() encrypted_text = encrypter.encrypt(plain_text, cek) self.assertEqual(plain_text, decrypter.decrypt(encrypted_text, cek))
class EncryptedStorage(DatabaseStorage): def __init__(self): self.encryption = JWEDirEncrypter() self.decryption = JWEDirDecrypter() def store(self, data, user_id, user_ik): encrypted_data = self.encrypt_data(user_id, user_ik, data) super(EncryptedStorage, self).store(encrypted_data, user_id) def get(self, user_id, user_ik): data = super(EncryptedStorage, self).get(user_id) if 'data' in data: decrypted_data = self.decrypt_data(user_id, user_ik, data) json_data = json.loads(decrypted_data) return json_data else: return {} def encrypt_data(self, user_id, user_ik, data): sha_key = generate_key(user_id, user_ik) encrypted = self.encryption.encrypt(json.dumps(data), sha_key) return {'data': encrypted} def decrypt_data(self, user_id, user_ik, encrypted_data): sha_key = generate_key(user_id, user_ik) return self.decryption.decrypt(encrypted_data['data'], sha_key)
class EncryptedQuestionnaireStorage(QuestionnaireStorage): def __init__(self, user_id, user_ik): super().__init__(user_id) if user_ik is None: raise ValueError('User ik must be set') self.encryption = JWEDirEncrypter() self.decryption = JWEDirDecrypter() self.user_ik = user_ik def add_or_update(self, data): encrypted_data = self.encrypt_data(data) super(EncryptedQuestionnaireStorage, self).add_or_update(encrypted_data) def get_user_data(self): data = super(EncryptedQuestionnaireStorage, self).get_user_data() if 'data' in data: decrypted_data = self.decrypt_data(self.user_id, self.user_ik, data) return decrypted_data def encrypt_data(self, data): sha_key = generate_key(self.user_id, self.user_ik) encrypted = self.encryption.encrypt(data, sha_key) return {'data': encrypted} def decrypt_data(self, user_id, user_ik, encrypted_data): sha_key = generate_key(user_id, user_ik) return self.decryption.decrypt(encrypted_data['data'], sha_key)
def __init__(self): self.encryption = JWEDirEncrypter() self.decryption = JWEDirDecrypter()
def _decrypt_data(self, encrypted_data): return JWEDirDecrypter().decrypt(encrypted_data['data'], self._cek)