1 // Copyright 2015 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef BASE_BASE64URL_H_ 6 #define BASE_BASE64URL_H_ 7 8 #include <optional> 9 #include <string> 10 #include <vector> 11 12 #include "base/base_export.h" 13 #include "base/containers/span.h" 14 #include "base/strings/string_piece.h" 15 16 namespace base { 17 18 enum class Base64UrlEncodePolicy { 19 // Include the trailing padding in the output, when necessary. 20 INCLUDE_PADDING, 21 22 // Remove the trailing padding from the output. 23 OMIT_PADDING 24 }; 25 26 // Encodes the |input| binary data in base64url, defined in RFC 4648: 27 // https://tools.ietf.org/html/rfc4648#section-5 28 // 29 // The |policy| defines whether padding should be included or omitted from the 30 // encoded |*output|. |input| and |*output| may reference the same storage. 31 BASE_EXPORT void Base64UrlEncode(span<const uint8_t> input, 32 Base64UrlEncodePolicy policy, 33 std::string* output); 34 35 // Same as the previous function, but accepts an input string. 36 BASE_EXPORT void Base64UrlEncode(StringPiece input, 37 Base64UrlEncodePolicy policy, 38 std::string* output); 39 40 enum class Base64UrlDecodePolicy { 41 // Require inputs contain trailing padding if non-aligned. 42 REQUIRE_PADDING, 43 44 // Accept inputs regardless of whether or not they have the correct padding. 45 IGNORE_PADDING, 46 47 // Reject inputs if they contain any trailing padding. 48 DISALLOW_PADDING 49 }; 50 51 // Decodes the |input| string in base64url, defined in RFC 4648: 52 // https://tools.ietf.org/html/rfc4648#section-5 53 // 54 // The |policy| defines whether padding will be required, ignored or disallowed 55 // altogether. |input| and |*output| may reference the same storage. 56 [[nodiscard]] BASE_EXPORT bool Base64UrlDecode(StringPiece input, 57 Base64UrlDecodePolicy policy, 58 std::string* output); 59 60 // Same as the previous function, but writing to a `std::vector`. 61 [[nodiscard]] BASE_EXPORT std::optional<std::vector<uint8_t>> Base64UrlDecode( 62 StringPiece input, 63 Base64UrlDecodePolicy policy); 64 65 } // namespace base 66 67 #endif // BASE_BASE64URL_H_ 68