Debian Codegraph @

mlspp/lib/hpke/src/base64.cpp

raw symbols SCIP
1 #include <hpke/base64.h>
2
3 #include "openssl_common.h"
4
5 #include <openssl/bio.h>
6 #include <openssl/err.h>
7 #include <openssl/evp.h>
8
9 namespace mlspp::hpke {
10
11 std::string
12 to_base64(const bytes& data)
13 {
14 if (data.empty()) {
15 return "";
16 }
17
18 #if WITH_BORINGSSL
19 const auto data_size = data.size();
20 #else
21 const auto data_size = static_cast<int>(data.size());
22 #endif
23
24 // base64 encoding produces 4 characters for every 3 input bytes (rounded up)
25 const auto out_size = (data_size + 2) / 3 * 4;
26 auto out = bytes(out_size + 1); // NUL terminator
27
28 const auto result = EVP_EncodeBlock(out.data(), data.data(), data_size);
29 if (result != out_size) {
30 throw openssl_error();
31 }
32
33 out.resize(out.size() - 1); // strip NUL terminator
34 return to_ascii(out);
35 }
36
37 std::string
38 to_base64url(const bytes& data)
39 {
40 if (data.empty()) {
41 return "";
42 }
43
44 auto encoded = to_base64(data);
45
46 auto pad_start = encoded.find_first_of('=');
47 if (pad_start != std::string::npos) {
48 encoded = encoded.substr(0, pad_start);
49 }
50
51 std::replace(encoded.begin(), encoded.end(), '+', '-');
52 std::replace(encoded.begin(), encoded.end(), '/', '_');
53
54 return encoded;
55 }
56
57 bytes
58 from_base64(const std::string& enc)
59 {
60 if (enc.length() == 0) {
61 return {};
62 }
63
64 if (enc.length() % 4 != 0) {
65 throw std::runtime_error("Base64 length is not divisible by 4");
66 }
67
68 const auto in = from_ascii(enc);
69 const auto in_size = static_cast<int>(in.size());
70 const auto out_size = in_size / 4 * 3;
71 auto out = bytes(out_size);
72
73 const auto result = EVP_DecodeBlock(out.data(), in.data(), in_size);
74 if (result != out_size) {
75 throw openssl_error();
76 }
77
78 if (enc.substr(enc.length() - 2, enc.length()) == "==") {
79 out.resize(out.size() - 2);
80 } else if (enc.substr(enc.length() - 1, enc.length()) == "=") {
81 out.resize(out.size() - 1);
82 }
83
84 return out;
85 }
86
87 bytes
88 from_base64url(const std::string& enc)
89 {
90 if (enc.empty()) {
91 return {};
92 }
93
94 auto enc_copy = enc;
95 std::replace(enc_copy.begin(), enc_copy.end(), '-', '+');
96 std::replace(enc_copy.begin(), enc_copy.end(), '_', '/');
97
98 while (enc_copy.length() % 4 != 0) {
99 enc_copy += "=";
100 }
101
102 return from_base64(enc_copy);
103 }
104
105 } // namespace mlspp::hpke