azure-core
Loading...
Searching...
No Matches
base64.hpp
Go to the documentation of this file.
1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
10#pragma once
11
12#include <algorithm>
13#include <cstdint> // defines std::uint8_t
14#include <stdexcept>
15#include <stdint.h> // deprecated, defines uint8_t in global namespace. TODO: Remove when uint8_t in the global namespace is removed.
16#include <string>
17#include <vector>
18
19namespace Azure { namespace Core {
20
28 class Convert final {
29 private:
30 // This type currently only contains static methods and hence disallowing instance creation.
35 Convert() = default;
36
37 public:
44 static std::string Base64Encode(const std::vector<uint8_t>& data);
45
52 static std::vector<uint8_t> Base64Decode(const std::string& text);
53 };
54
55 namespace _internal {
63 class Convert final {
64 private:
65 // This type currently only contains static methods and hence disallowing instance creation.
70 Convert() = default;
71
72 public:
79 static std::string Base64Encode(const std::string& data);
80 };
81
86 class Base64Url final {
87
88 public:
89 static std::string Base64UrlEncode(const std::vector<uint8_t>& data)
90 {
91 auto base64 = Azure::Core::Convert::Base64Encode(data);
92 // update to base64url
93 auto trail = base64.find('=');
94 if (trail != std::string::npos)
95 {
96 base64 = base64.substr(0, trail);
97 }
98 std::replace(base64.begin(), base64.end(), '+', '-');
99 std::replace(base64.begin(), base64.end(), '/', '_');
100 return base64;
101 }
102
103 static std::vector<uint8_t> Base64UrlDecode(const std::string& text)
104 {
105 std::string base64url(text);
106 // base64url to base64
107 std::replace(base64url.begin(), base64url.end(), '-', '+');
108 std::replace(base64url.begin(), base64url.end(), '_', '/');
109 switch (base64url.size() % 4)
110 {
111 case 0:
112 break;
113 case 2:
114 base64url.append("==");
115 break;
116 case 3:
117 base64url.append("=");
118 break;
119 default:
120 throw std::invalid_argument("Unexpected Base64URL encoding in the HTTP response.");
121 }
122 return Azure::Core::Convert::Base64Decode(base64url);
123 }
124 };
125 } // namespace _internal
126
127}} // namespace Azure::Core
Used to convert one form of data into another, for example encoding binary data into Base64 encoded o...
Definition base64.hpp:28
static std::string Base64Encode(const std::vector< uint8_t > &data)
Encodes a vector of binary data using Base64.
Definition base64.cpp:492
static std::vector< uint8_t > Base64Decode(const std::string &text)
Decodes a Base64 encoded data into a vector of binary data.
Definition base64.cpp:497
Compute the hash value for the input binary data, using SHA256, SHA384 and SHA512.
Definition azure_assert.hpp:57