3 [](https://travis-ci.org/tplgy/cppcodec) [](https://ci.appveyor.com/project/efidler/cppcodec)
5 Header-only C++11 library to encode/decode base64, base64url, base32, base32hex
6 and hex (a.k.a. base16) as specified in RFC 4648, plus Crockford's base32.
8 MIT licensed with consistent, flexible API. Supports raw pointers,
9 `std::string` and (templated) character vectors without unnecessary allocations.
15 1. Import cppcodec into your project (copy, git submodule, etc.)
16 2. Add the cppcodec root directory to your build system's list of include directories
17 3. Include headers and start using the API.
19 Since cppcodec is a header-only library, no extra build step is needed.
20 Alternatively, you can install the headers and build extra tools/tests with CMake.
26 A number of codec variants exist for base64 and base32, defining different alphabets
27 or specifying the use of padding and line breaks in different ways. cppcodec is designed
28 to let you make a conscious choice about which one you're using, but assumes you will
29 mostly stick to a single one.
31 cppcodec's approach is to implement encoding/decoding algorithms in different namespaces
32 (e.g. `cppcodec::base64_rfc4648`) and in addition to the natural headers, also offer
33 convenience headers to define a shorthand alias (e.g. `base64`) for one of the variants.
35 Here is an expected standard use of cppcodec:
38 #include <cppcodec/base32_default_crockford.hpp>
39 #include <cppcodec/base64_default_rfc4648.hpp>
43 std::vector<uint8_t> decoded = base64::decode("YW55IGNhcm5hbCBwbGVhc3VyZQ==");
44 std::cout << "decoded size (\"any carnal pleasure\"): " << decoded.size() << '\n';
45 std::cout << base32::encode(decoded) << std::endl; // "C5Q7J833C5S6WRBC41R6RSB1EDTQ4S8"
50 If possible, avoid including "default" headers in other header files.
52 Non-aliasing headers omit the "default" part, e.g. `<cppcodec/base64_rfc4648.hpp>`
53 or `<cppcodec/hex_lower.hpp>`. Currently supported variants are:
57 * `base64_rfc4648` uses the PEM/MIME/UTF-7 alphabet, that is (in order)
58 A-Z, a-z, 0-9 plus characters '+' and '/'. This is what's usually considered
59 the "standard base64" that you see everywhere and requires padding ('=') but
60 no line breaks. Whitespace and other out-of-alphabet symbols are regarded as
62 * `base64_url` is the same as `base64_rfc4648` (and defined in the same RFC)
63 but uses '-' (minus) and '_' (underscore) as special characters instead of
64 '+' and '/'. This is safe to use for URLs and file names. Padding with '=' is
65 required, it will be generated when encoding to a string and regarded as a
66 parse error if it's not present when decoding.
67 * `base64_url_unpadded` variant is the same as `base64_url`, but '=' padding
68 characters are optional. When encoding, no padding will be appended to the
69 resulting string. Decoding accepts either padded or unpadded strings.
73 All base32 variants encode 5 bits as one (8-bit) character, which results in
74 an encoded length of roughly 160% (= 8/5). Their selling point is mainly
75 case-insensitive decoding, no special characters and alphabets that can be
76 communicated via phone.
78 * `base32_rfc4648` implements the popular, standardized variant defined in
79 RFC 4648. It uses the full upper-case alphabet A-Z for the first 26 values
80 and the digit characters 2-7 for the last ten. Padding with '=' is required
81 and makes the encoded string a multiple of 8 characters. The codec accepts
82 no invalid symbols, so if you want to let the user enter base32 data then
83 consider replacing numbers '0', '1' and '8' with 'O', 'I' and 'B' on input.
84 * `base32_crockford` implements [Crockford base32](http://www.crockford.com/wrmg/base32.html).
85 It's less widely used than the RFC 4648 alphabet, but offers a more carefully
86 picked alphabet and also defines decoding similar characters 'I', 'i', 'L'
87 'l' as '1' plus 'O' and 'o' as '0' so no care is required for user input.
88 Crockford base32 does not use '=' padding. Checksums are not implemented.
89 Note that the specification is ambiguous about whether to pad bit quintets to
90 the left or to the right, i.e. whether the codec is a place-based single number
91 encoding system or a concatenative iterative stream encoder. This codec variant
92 picks the streaming interpretation and thus zero-pads on the right. (See
93 http://merrigrove.blogspot.ca/2014/04/what-heck-is-base64-encoding-really.html
94 for a detailed discussion of the issue.)
95 * `base32_hex` is the logical extension of the hexadecimal alphabet, and also
96 specified in RFC 4648. It uses the digit characters 0-9 for the first 10 values
97 and the upper-case letters A-V for the remaining ones. The alphabet is
98 conceptually simple, but contains all of the ambiguous number/letter pairs that
99 the other variants try to avoid. It is also less suitable for verbal
100 transmission. Padding with '=' is required and makes the encoded string a
101 multiple of 8 characters.
105 * `hex_upper` outputs upper-case letters and accepts lower-case as well.
106 This is an octet-streaming codec variant and for decoding, requires an even
107 number of input symbols. In other words, don't try to decode (0x)"F",
108 (0x)"10F" etc. with this variant, use a place-based single number codec
109 instead if you want to do this. Also, you are expected to prepend and remove
110 a "0x" prefix externally as it won't be generated when encoding / will be
111 rejected when decoding.
112 * `hex_lower` outputs lower-case letters and accepts upper-case as well.
113 Similar to `hex_upper`, it's stream-based (no odd symbol lengths) and does
114 not deal with "0x" prefixes.
120 All codecs expose the same API. In the below documentation, replace `<codec>` with a
121 default alias such as `base64`, `base32` or `hex`, or with the full namespace such as
122 `cppcodec::base64_rfc4648` or `cppcodec::base32_crockford`.
124 For templated parameters `T` and `Result`, you can use e.g. `std::vector<uint8_t>`,
125 `std::string` or anything that supports:
126 * `.data()` and `.size()` for `T` (read-only) template parameters,
127 * for `Result` template parameters, also `.reserve(size_t)`, `.resize(size_t)`
128 and `.push_back([uint8_t|char])`.
130 It's possible to support types lacking these functions, consult the code directly if you need this.
136 // Convenient version, returns an std::string.
137 std::string <codec>::encode(const [uint8_t|char]* binary, size_t binary_size);
138 std::string <codec>::encode(const T& binary);
140 // Convenient version with templated result type.
141 Result <codec>::encode<Result>(const [uint8_t|char]* binary, size_t binary_size);
142 Result <codec>::encode<Result>(const T& binary);
144 // Reused result container version. Resizes encoded_result before writing to it.
145 void <codec>::encode(Result& encoded_result, const [uint8_t|char]* binary, size_t binary_size);
146 void <codec>::encode(Result& encoded_result, const T& binary);
149 Encode binary data into an encoded (base64/base32/hex) string.
150 Won't throw by itself, but the result type might throw on `.resize()`.
153 size_t <codec>::encode(char* encoded_result, size_t encoded_buffer_size, const [uint8_t|char]* binary, size_t binary_size) noexcept;
154 size_t <codec>::encode(char* encoded_result, size_t encoded_buffer_size, const T& binary) noexcept;
157 Encode binary data into pre-allocated memory with a buffer size of
158 `<codec>::encoded_size(binary_size)` or larger.
160 Returns the byte size of the encoded string excluding null termination,
161 which is equal to `<codec>::encoded_size(binary_size)`.
163 If `encoded_buffer_size` is larger than required, a single null termination character (`'\0'`)
164 is written after the last encoded character. The `encoded_size()` function ensures that the required
165 buffer size is large enough to hold the padding required for the respective codec variant.
166 Provide a buffer of size `encoded_size() + 1` to make it a null-terminated C string.
168 Calls abort() if `encoded_buffer_size` is insufficient. (That way, the function can remain `noexcept`
169 rather than throwing on an entirely avoidable error condition.)
172 size_t <codec>::encoded_size(size_t binary_size) noexcept;
175 Calculate the (exact) length of the encoded string based on binary size,
176 excluding null termination but including padding (if specified by the codec variant).
182 // Convenient version, returns an std::vector<uint8_t>.
183 std::vector<uint8_t> <codec>::decode(const char* encoded, size_t encoded_size);
184 std::vector<uint8_t> <codec>::decode(const T& encoded);
186 // Convenient version with templated result type.
187 Result <codec>::decode<Result>(const char* encoded, size_t encoded_size);
188 Result <codec>::decode<Result>(const T& encoded);
190 // Reused result container version. Resizes binary_result before writing to it.
191 void <codec>::decode(Result& binary_result, const char* encoded, size_t encoded_size);
192 void <codec>::decode(Result& binary_result, const T& encoded);
195 Decode an encoded (base64/base32/hex) string into a binary buffer.
197 Throws a cppcodec::parse_error exception (inheriting from std::domain_error)
198 if the input data does not conform to the codec variant specification.
199 Also, the result type might throw on `.resize()`.
202 size_t <codec>::decode([uint8_t|char]* binary_result, size_t binary_buffer_size, const char* encoded, size_t encoded_size);
203 size_t <codec>::decode([uint8_t|char]* binary_result, size_t binary_buffer_size, const T& encoded);
206 Decode an encoded string into pre-allocated memory with a buffer size of
207 `<codec>::decoded_max_size(encoded_size)` or larger.
209 Returns the byte size of the decoded binary data, which is less or equal to
210 `<codec>::decoded_max_size(encoded_size)`.
212 Calls abort() if `binary_buffer_size` is insufficient, for consistency with encode().
213 Throws a cppcodec::parse_error exception (inheriting from std::domain_error)
214 if the input data does not conform to the codec variant specification.
217 size_t <codec>::decoded_max_size(size_t encoded_size) noexcept;
220 Calculate the maximum size of the decoded binary buffer based on the encoded string length.
222 If the codec variant does not allow padding or whitespace / line breaks,
223 the maximum decoded size will be the exact decoded size.
225 If the codec variant allows padding or whitespace / line breaks, the actual decoded size
226 might be smaller. If you're using the pre-allocated memory result call, make sure to take
227 its return value (the actual decoded size) into account.