#include "../include/Encryption.hpp" #include #include #include namespace odhtdb { Encryption::Encryption(const DataView &data, const DataView &additionalData) { cipherText = new unsigned char[crypto_aead_xchacha20poly1305_ietf_ABYTES + data.size]; crypto_aead_xchacha20poly1305_ietf_keygen(key); randombytes_buf(nonce, NONCE_BYTE_SIZE); if(crypto_aead_xchacha20poly1305_ietf_encrypt(cipherText, &cipherTextLength, (const unsigned char*)data.data, data.size, (const unsigned char*)additionalData.data, additionalData.size, nullptr, nonce, key) != 0) throw EncryptionException("Failed to encrypt data"); } Encryption::~Encryption() { delete[](cipherText); } DataView Encryption::getKey() const { return DataView((void*)key, KEY_BYTE_SIZE); } DataView Encryption::getNonce() const { return DataView((void*)nonce, NONCE_BYTE_SIZE); } DataView Encryption::getCipherText() const { return DataView((void*)cipherText, cipherTextLength); } Decryption::Decryption(const DataView &data, const DataView &nonce, const DataView &key) { decryptedText = new unsigned char[data.size]; if(nonce.size < NONCE_BYTE_SIZE) throw DecryptionException("Nonce is not big enough"); if(key.size < KEY_BYTE_SIZE) throw DecryptionException("Key is not big enough"); if(crypto_aead_xchacha20poly1305_ietf_decrypt(decryptedText, &decryptedTextLength, nullptr, (const unsigned char*)data.data, data.size, nullptr, 0, (const unsigned char*)nonce.data, (const unsigned char*)key.data) != 0) throw DecryptionException("Failed to decrypt data"); } Decryption::~Decryption() { delete[](decryptedText); } DataView Decryption::getDecryptedText() const { return DataView((void*)decryptedText, decryptedTextLength); } }