Botan 3.4.0
Crypto and TLS for C&
uuid.cpp
Go to the documentation of this file.
1/*
2* UUID type
3* (C) 2015,2018 Jack Lloyd
4*
5* Botan is released under the Simplified BSD License (see license.txt)
6*/
7
8#include <botan/uuid.h>
9
10#include <botan/hex.h>
11#include <botan/rng.h>
12#include <botan/internal/fmt.h>
13#include <sstream>
14
15namespace Botan {
16
18 m_uuid.resize(16);
19 rng.randomize(m_uuid.data(), m_uuid.size());
20
21 // Mark as a random v4 UUID (RFC 4122 sec 4.4)
22 m_uuid[6] = 0x40 | (m_uuid[6] & 0x0F);
23
24 // Set reserved bits
25 m_uuid[8] = 0x80 | (m_uuid[8] & 0x3F);
26}
27
28UUID::UUID(const std::vector<uint8_t>& blob) {
29 if(blob.size() != 16) {
30 throw Invalid_Argument("Bad UUID blob " + hex_encode(blob));
31 }
32
33 m_uuid = blob;
34}
35
36UUID::UUID(std::string_view uuid_str) {
37 if(uuid_str.size() != 36 || uuid_str[8] != '-' || uuid_str[13] != '-' || uuid_str[18] != '-' ||
38 uuid_str[23] != '-') {
39 throw Invalid_Argument(fmt("Bad UUID '{}'", uuid_str));
40 }
41
42 std::string just_hex;
43 for(char c : uuid_str) {
44 if(c == '-') {
45 continue;
46 }
47
48 just_hex += c;
49 }
50
51 m_uuid = hex_decode(just_hex);
52
53 if(m_uuid.size() != 16) {
54 throw Invalid_Argument(fmt("Bad UUID '{}'", uuid_str));
55 }
56}
57
58std::string UUID::to_string() const {
59 if(is_valid() == false) {
60 throw Invalid_State("UUID object is empty cannot convert to string");
61 }
62
63 const std::string raw = hex_encode(m_uuid);
64
65 std::ostringstream formatted;
66
67 for(size_t i = 0; i != raw.size(); ++i) {
68 if(i == 8 || i == 12 || i == 16 || i == 20) {
69 formatted << "-";
70 }
71 formatted << raw[i];
72 }
73
74 return formatted.str();
75}
76
77} // namespace Botan
void randomize(std::span< uint8_t > output)
Definition rng.h:52
bool is_valid() const
Definition uuid.h:57
std::string to_string() const
Definition uuid.cpp:58
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53
void hex_encode(char output[], const uint8_t input[], size_t input_length, bool uppercase)
Definition hex.cpp:33
size_t hex_decode(uint8_t output[], const char input[], size_t input_length, size_t &input_consumed, bool ignore_ws)
Definition hex.cpp:81