Botan  2.10.0
Crypto and TLS for C++11
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 
13 namespace Botan {
14 
15 UUID::UUID(RandomNumberGenerator& rng)
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 
27 UUID::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 
37 UUID::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(size_t i = 0; i != uuid_str.size(); ++i)
50  {
51  char c = uuid_str[i];
52 
53  if(c == '-')
54  continue;
55 
56  just_hex += c;
57  }
58 
59  m_uuid = hex_decode(just_hex);
60 
61  if(m_uuid.size() != 16)
62  {
63  throw Invalid_Argument("Bad UUID '" + uuid_str + "'");
64  }
65  }
66 
67 std::string UUID::to_string() const
68  {
69  if(is_valid() == false)
70  throw Invalid_State("UUID object is empty cannot convert to string");
71 
72  std::string h = hex_encode(m_uuid);
73 
74  h.insert(8, "-");
75  h.insert(13, "-");
76  h.insert(18, "-");
77  h.insert(23, "-");
78 
79  return h;
80  }
81 
82 }
void hex_encode(char output[], const uint8_t input[], size_t input_length, bool uppercase)
Definition: hex.cpp:14
bool RandomNumberGenerator & rng
Definition: numthry.h:176
std::string to_string() const
Definition: uuid.cpp:67
BigInt const BigInt const BigInt & h
Definition: rfc6979.h:47
Definition: alg_id.cpp:13
size_t hex_decode(uint8_t output[], const char input[], size_t input_length, size_t &input_consumed, bool ignore_ws)
Definition: hex.cpp:49
BigInt const BigInt const BigInt & c
Definition: numthry.h:25
UUID()
Definition: uuid.h:25
bool is_valid() const
Definition: uuid.h:59