azure-core
base64.hpp
Go to the documentation of this file.
1 // Copyright (c) Microsoft Corporation. All rights reserved.
2 // SPDX-License-Identifier: MIT
3 
10 #pragma once
11 
12 #include <algorithm>
13 #include <stdexcept>
14 #include <string>
15 #include <vector>
16 
17 namespace Azure { namespace Core {
18 
23  class Convert final {
24  private:
25  // This type currently only contains static methods and hence disallowing instance creation.
30  Convert() = default;
31 
32  public:
39  static std::string Base64Encode(const std::vector<uint8_t>& data);
40 
47  static std::vector<uint8_t> Base64Decode(const std::string& text);
48  };
49 
50  namespace _internal {
51 
56  class Base64Url final {
57 
58  public:
59  static std::string Base64UrlEncode(const std::vector<uint8_t>& data)
60  {
61  auto base64 = Azure::Core::Convert::Base64Encode(data);
62  // update to base64url
63  auto trail = base64.find('=');
64  if (trail != std::string::npos)
65  {
66  base64 = base64.substr(0, trail);
67  }
68  std::replace(base64.begin(), base64.end(), '+', '-');
69  std::replace(base64.begin(), base64.end(), '/', '_');
70  return base64;
71  }
72 
73  static std::vector<uint8_t> Base64UrlDecode(const std::string& text)
74  {
75  std::string base64url(text);
76  // base64url to base64
77  std::replace(base64url.begin(), base64url.end(), '-', '+');
78  std::replace(base64url.begin(), base64url.end(), '_', '/');
79  switch (base64url.size() % 4)
80  {
81  case 0:
82  break;
83  case 2:
84  base64url.append("==");
85  break;
86  case 3:
87  base64url.append("=");
88  break;
89  default:
90  throw std::invalid_argument("Unexpected Base64URL encoding in the HTTP response.");
91  }
92  return Azure::Core::Convert::Base64Decode(base64url);
93  }
94  };
95  } // namespace _internal
96 
97 }} // namespace Azure::Core
Azure
Azure SDK abstractions.
Definition: azure_assert.hpp:55
Azure::Core::Convert::Base64Decode
static std::vector< uint8_t > Base64Decode(const std::string &text)
Decodes the UTF-8 encoded text represented as Base64 into binary data.
Definition: base64.cpp:496
Azure::Core::Convert::Base64Encode
static std::string Base64Encode(const std::vector< uint8_t > &data)
Encodes the vector of binary data into UTF-8 encoded text represented as Base64.
Definition: base64.cpp:491
Azure::Core::Convert
Used to convert one form of data into another, for example encoding binary data into Base64 text.
Definition: base64.hpp:23