#pragma once /* * Encrypts/decrypts data using xchacha20-poly1305 ietf */ #include "DataView.hpp" #include "utils.hpp" #include #include namespace odhtdb { const int ENCRYPTION_CHECKSUM_BYTE_SIZE = 16; const int ENCRYPTION_NONCE_BYTE_SIZE = 24; const int ENCRYPTION_KEY_BYTE_SIZE = 32; class EncryptionException : public std::runtime_error { public: EncryptionException(const std::string &errMsg) : std::runtime_error(errMsg) {} }; class DecryptionException : public std::runtime_error { public: DecryptionException(const std::string &errMsg) : std::runtime_error(errMsg) {} }; class Encryption { DISABLE_COPY(Encryption) public: // Throws EncryptionException on failure (or std::bad_alloc on failed memory allocation) Encryption(const DataView &data, const DataView &key = DataView()); ~Encryption(); DataView getKey() const; DataView getNonce() const; DataView getCipherText() const; // Size of output should be at least @ENCRYPTION_KEY_BYTE_SIZE bytes static void generateKey(unsigned char *output); private: unsigned char key[ENCRYPTION_KEY_BYTE_SIZE]; unsigned char nonce[ENCRYPTION_NONCE_BYTE_SIZE]; unsigned char *cipherText; unsigned long long cipherTextLength; }; class Decryption { DISABLE_COPY(Decryption) public: Decryption() : decryptedText(nullptr), decryptedTextLength(0) {} // Throws DecryptionException on failure Decryption(const DataView &data, const DataView &nonce, const DataView &key); Decryption(Decryption &&other); Decryption& operator=(Decryption &&other); ~Decryption(); DataView getDecryptedText() const; private: unsigned char *decryptedText; unsigned long long decryptedTextLength; }; }