aboutsummaryrefslogtreecommitdiff
path: root/src/Encryption.cpp
blob: 8e87a8d847fba377cdd30604169009284a97e9e2 (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
#include "../include/Encryption.hpp"
#include <sodium/crypto_stream_xchacha20.h>
#include <sodium/randombytes.h>
#include <string>

namespace odhtdb
{
    void generateEncryptionKey(EncryptionKey *output)
    {
        if(!output) return;
        crypto_stream_xchacha20_keygen((unsigned char*)output);
    }
    
    int encrypt(EncryptedData *output, const EncryptionKey *key, const void *data, size_t dataSize)
    {
        if(!output || !key) return -1;
        if(dataSize == 0) return 0;
        output->data.resize(dataSize);
        randombytes_buf(output->nonce, NONCE_BYTE_SIZE);
        return crypto_stream_xchacha20_xor((unsigned char*)&output->data[0], (const unsigned char*)data, dataSize, (const unsigned char*)output->nonce, (const unsigned char*)key);
    }
    
    int decrypt(std::string *output, const EncryptionKey *key, const EncryptedData *encryptedData)
    {
        if(!encryptedData || !key || !output) return -1;
        if(encryptedData->data.empty()) return 0;
        output->resize(encryptedData->data.size());
        return crypto_stream_xchacha20_xor((unsigned char*)&(*output)[0], (const unsigned char*)&encryptedData->data[0], encryptedData->data.size(), (const unsigned char*)encryptedData->nonce, (const unsigned char*)key);
    }
}