Botan 3.0.0-alpha0
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#include <botan/rng.h>
10#include <botan/hex.h>
11#include <sstream>
12
13namespace Botan {
14
16 {
17 m_uuid.resize(16);
18 rng.randomize(m_uuid.data(), m_uuid.size());
19
20 // Mark as a random v4 UUID (RFC 4122 sec 4.4)
21 m_uuid[6] = 0x40 | (m_uuid[6] & 0x0F);
22
23 // Set reserved bits
24 m_uuid[8] = 0x80 | (m_uuid[8] & 0x3F);
25 }
26
27UUID::UUID(const std::vector<uint8_t>& blob)
28 {
29 if(blob.size() != 16)
30 {
31 throw Invalid_Argument("Bad UUID blob " + hex_encode(blob));
32 }
33
34 m_uuid = blob;
35 }
36
37UUID::UUID(const std::string& uuid_str)
38 {
39 if(uuid_str.size() != 36 ||
40 uuid_str[8] != '-' ||
41 uuid_str[13] != '-' ||
42 uuid_str[18] != '-' ||
43 uuid_str[23] != '-')
44 {
45 throw Invalid_Argument("Bad UUID '" + uuid_str + "'");
46 }
47
48 std::string just_hex;
49 for(char c : uuid_str)
50 {
51 if(c == '-')
52 continue;
53
54 just_hex += c;
55 }
56
57 m_uuid = hex_decode(just_hex);
58
59 if(m_uuid.size() != 16)
60 {
61 throw Invalid_Argument("Bad UUID '" + uuid_str + "'");
62 }
63 }
64
65std::string UUID::to_string() const
66 {
67 if(is_valid() == false)
68 throw Invalid_State("UUID object is empty cannot convert to string");
69
70 std::string h = hex_encode(m_uuid);
71
72 h.insert(8, "-");
73 h.insert(13, "-");
74 h.insert(18, "-");
75 h.insert(23, "-");
76
77 return h;
78 }
79
80}
virtual void randomize(uint8_t output[], size_t length)=0
UUID()
Definition: uuid.h:27
bool is_valid() const
Definition: uuid.h:61
std::string to_string() const
Definition: uuid.cpp:65
Definition: alg_id.cpp:13
void hex_encode(char output[], const uint8_t input[], size_t input_length, bool uppercase)
Definition: hex.cpp:31
size_t hex_decode(uint8_t output[], const char input[], size_t input_length, size_t &input_consumed, bool ignore_ws)
Definition: hex.cpp:89