aboutsummaryrefslogtreecommitdiff
path: root/include/odhtdb/Encryption.hpp
blob: b2ae67e7cb370ae36f2ebf980b1a664e3b2543a1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#pragma once

/*
 * Encrypts/decrypts data using xchacha20-poly1305 ietf
 */

#include "DataView.hpp"
#include "utils.hpp"
#include <string>
#include <stdexcept>

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;
    };
}