Project SkyFire Core
SkyFire 5.4.8 server core API documentation
Loading...
Searching...
No Matches
CryptoGenerics.h
Go to the documentation of this file.
1/*
2* This file is part of Project SkyFire https://www.projectskyfire.org.
3* See LICENSE.md file for Copyright information
4*/
5
6#ifndef _CRYPTO_GENERICS_HPP
7#define _CRYPTO_GENERICS_HPP
8
9#include "BigNumber.h"
10#include "CryptoRandom.h"
11#include "Define.h"
12#include "Errors.h"
13#include <iterator>
14#include <vector>
15
17{
19 {
20 template <typename Cipher>
21 static typename Cipher::IV GenerateRandomIV()
22 {
23 typename Cipher::IV iv;
25 return iv;
26 }
27
28 template <typename Container>
29 static void AppendToBack(std::vector<uint8>& data, Container const& tail)
30 {
31 data.insert(data.end(), std::begin(tail), std::end(tail));
32 }
33
34 template <typename Container>
35 static void SplitFromBack(std::vector<uint8>& data, Container& tail)
36 {
37 ASSERT(data.size() >= std::size(tail));
38 for (size_t i = 1, N = std::size(tail); i <= N; ++i)
39 {
40 tail[N - i] = data.back();
41 data.pop_back();
42 }
43 }
44 };
45}
46
47namespace SkyFire::Crypto
48{
49 template <typename Cipher>
50 void AEEncryptWithRandomIV(std::vector<uint8>& data, typename Cipher::Key const& key)
51 {
52 using IV = typename Cipher::IV;
53 using Tag = typename Cipher::Tag;
54 // select random IV
56 Tag tag;
57
58 // encrypt data
59 Cipher cipher(true);
60 cipher.Init(key);
61 bool success = cipher.Process(iv, data.data(), data.size(), tag);
62 ASSERT(success);
63
64 // append trailing IV and tag
67 }
68
69 template <typename Cipher>
70 void AEEncryptWithRandomIV(std::vector<uint8>& data, BigNumber const& key)
71 {
72 AEEncryptWithRandomIV<Cipher>(data, key.ToByteArray<Cipher::KEY_SIZE_BYTES>());
73 }
74
75 template <typename Cipher>
76 bool AEDecrypt(std::vector<uint8>& data, typename Cipher::Key const& key)
77 {
78 using IV = typename Cipher::IV;
79 using Tag = typename Cipher::Tag;
80 // extract trailing IV and tag
81 IV iv;
82 Tag tag;
85
86 // decrypt data
87 Cipher cipher(false);
88 cipher.Init(key);
89 return cipher.Process(iv, data.data(), data.size(), tag);
90 }
91
92 template <typename Cipher>
93 bool AEDecrypt(std::vector<uint8>& data, BigNumber const& key)
94 {
95 return AEDecrypt<Cipher>(data, key.ToByteArray<Cipher::KEY_SIZE_BYTES>());
96 }
97}
98
99#endif
#define ASSERT
Definition Errors.h:29
std::array< uint8, Size > ToByteArray(bool littleEndian=true) const
Definition BigNumber.h:95
bool AEDecrypt(std::vector< uint8 > &data, typename Cipher::Key const &key)
std::array< uint8, S > GetRandomBytes()
void AEEncryptWithRandomIV(std::vector< uint8 > &data, typename Cipher::Key const &key)
static Cipher::IV GenerateRandomIV()
static void SplitFromBack(std::vector< uint8 > &data, Container &tail)
static void AppendToBack(std::vector< uint8 > &data, Container const &tail)