-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestBase64.cpp
More file actions
90 lines (83 loc) · 2.5 KB
/
TestBase64.cpp
File metadata and controls
90 lines (83 loc) · 2.5 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <iostream>
#include <vector>
#include <cstdint>
#include <string>
#include <sys/random.h>
#include <unistd.h>
#include "common/Base64.h"
#include "Utility.h"
#include <iomanip>
#include <optional>
using namespace TUI::Common::Base64;
static std::vector<std::uint8_t> GetRandomLengthRandomBytes(size_t minLength, size_t maxLength)
{
size_t value = 0;
if (getrandom(&value, sizeof(value), 0) != static_cast<ssize_t>(sizeof(value)))
{
throw std::runtime_error("Failed to get random bytes");
}
/** This is biased. But we are not doing a crypto operation. */
size_t length = minLength + (value % (maxLength - minLength + 1));
/** This might be too long. But that's your call. */
std::vector<std::uint8_t> data(length);
if (getrandom(data.data(), data.size(), 0) != static_cast<ssize_t>(data.size()))
{
throw std::runtime_error("Failed to get random bytes");
}
return data;
}
static void DumpBytes(const std::string& tag, const std::vector<std::uint8_t>& data)
{
std::cout << tag << ": " << std::dec << data.size() << " bytes" << std::endl;
for (const auto& byte : data)
{
std::cout << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(byte) << " ";
if (((&byte - data.data() + 1) % 16) == 0)
{
std::cout << std::endl;
}
}
std::cout << std::dec << std::endl;
}
int main(int argc, char const *argv[])
{
(void)argc;
(void)argv;
std::optional<std::vector<uint8_t>> data;
std::optional<std::string> encoded;
std::optional<std::vector<uint8_t>> decoded;
try
{
for (int i = 0; i < 1000; i++)
{
data.reset();
encoded.reset();
decoded.reset();
data = GetRandomLengthRandomBytes(0, 1000);
encoded = Encode(data.value());
decoded = Decode(encoded.value());
if (data != decoded)
{
throw std::runtime_error("Decoded data does not match the original data");
}
}
}
catch(const std::exception& e)
{
std::cout << e.what() << '\n';
if (data.has_value())
{
DumpBytes("Original Data", data.value());
}
if (encoded.has_value())
{
std::cout << "Encoded Data:" << std::endl << encoded.value() << std::endl;
}
if (decoded.has_value())
{
DumpBytes("Decoded Data", decoded.value());
}
return 1;
}
return 0;
}