Taskcore
Base64 encode and decode
Also called base64 encode, base64 decode, base64url, URL-safe base64, decode a base64 string, encode bytes as text.
Encode bytes as Base64 text in the standard or the URL-safe alphabet of RFC 4648, and decode the text strictly, so that bad characters, white space, wrong padding and non-zero pad bits are errors.
- Evidence
- Code in 10 languages
Task
Encode bytes as Base64 text, and decode the text back to the bytes. Each solution has two functions, encode(data, alphabet) and decode(text, alphabet). The data is an array of bytes, not a string. To encode text, first get its UTF-8 bytes (see UTF-8).
Base64 puts each group of 3 bytes, or 24 bits, into 4 characters of 6 bits. RFC 4648 defines two alphabets of 64 characters. Both give the values 0 to 61 to A to Z, a to z and 0 to 9. They differ in the values 62 and 63:
standard(section 4) uses+and/. The encoder pads the text with=to a multiple of 4 characters.url(section 5) uses-and_, which are safe in URLs and file names. The encoder adds no padding. This is the form of RFC 7515, which omits the trailing=and allows no line breaks or white space.
A last group of 1 byte gives 2 characters, and a last group of 2 bytes gives 3 characters. The last character then has bits that hold no data. These are the pad bits, and section 3.5 says that the encoder sets them to zero.
The decoder is strict. It accepts a text only when the encoder gives exactly that text for some bytes. So each byte string has one valid text in each alphabet. decode reports the error invalid for these inputs:
- a character outside the alphabet, for example
-in standard mode or+in url mode - white space and line breaks
- a missing, extra or misplaced
=, and any=in url mode - a length that is 1 mod 4, because one character holds only 6 bits
- a last character with pad bits that are not zero
RFC 4648 supports these rules. Section 3.3 says that an implementation must reject characters outside the base alphabet, unless the referring specification says otherwise. Section 12 says that a decoder that ignores such characters makes a covert channel possible. Section 3.5 allows a decoder to reject an encoding whose pad bits are not zero.
Solutions
- Python.
base64.b64encode, andbase64.urlsafe_b64encodewithrstrip("=")for url. The decoder callsbase64.b64decodewithvalidate=True, so a character outside the alphabet raises an error. For url mode it adds the padding and givesaltchars=b"-_".validate=Truestill accepts non-zero pad bits (see the pitfalls). So the solution encodes the result again and compares it with the text. Only the canonical text gives itself back, so this one check covers every rule of the contract. - JavaScript and TypeScript (Node.js).
buf.toString("base64")andbuf.toString("base64url"). The Node.js documentation says thatbase64urlomits the padding when it encodes.Buffer.from(text, encoding)decodes, but it accepts both alphabets and skips other characters. So the solution uses the same check: encode again and compare. The TypeScript file adds types only. - Java.
Base64.getEncoder()andBase64.getUrlEncoder().withoutPadding(). The decoders ofgetDecoder()andgetUrlDecoder()throwIllegalArgumentExceptionfor a character outside the alphabet. TheBase64.Decoderdocumentation says that they accept the padding but do not require it. So the solution adds the check. - C#.
Convert.ToBase64String, andBase64Url.EncodeToStringofSystem.Buffers.Text.Convert.FromBase64StringandBase64Url.DecodeFromCharsthrowFormatExceptionfor bad text. TheFromBase64Stringdocumentation says that it ignores white space. So the solution adds the check. - Go.
base64.StdEncoding, andbase64.RawURLEncoding, which the documentation describes as the url encoding with no padding characters. The decoder callsStrict(), which requires zero pad bits. TheStrictdocumentation adds that the decoder still ignores the new line characters CR and LF. So the solution rejects a text with\ror\nfirst. - Rust. The standard library has no Base64, so the solution implements it. The encoder takes 3 bytes at a time from a table of 64 characters. The decoder removes at most two
=in standard mode, and a lookup table of 256 entries rejects every other byte that is not in the alphabet. Then it checks the length and the pad bits. - C. The same algorithm as Rust.
b64_encodereturns a new string.b64_decodereturnsB64_OK,B64_INVALIDorB64_NO_MEMORY. Before themalloc,b64_encodechecks that the output size fits insize_t(see Integer overflow or wraparound). - C++. The same algorithm, with
std::span<const std::uint8_t>andstd::string_view.decodethrowsstd::invalid_argument. - Bash.
b64_encodesends the bytes on the standard input to thebase64command and removes every newline. GNUbase64wraps its output after 76 characters by default. For url mode, parameter expansion changes+and/and removes the padding.b64_decodefirst checks the text with one regular expression in[[ =~ ]]. The expression checks the alphabet, the length, the padding and the pad bits. Before==, the last data character must beA,Q,gorw, because their values are multiples of 16. Before=, its value must be a multiple of 4. Then the function changes-and_back, adds the padding and runsbase64 -d. The bracket expressions list each character, so the locale does not change them.
Edge cases
The cases of encode are in cases/basic.jsonl and cases/edge.jsonl. The bytes are lowercase hexadecimal, because the contract types have no type for bytes. Each test also decodes the result and checks that it gives the bytes back.
rfc-ftorfc-foobar: the test vectors of RFC 4648 section 10.empty-standardandempty-url: no bytes give the empty text.two-pad-chars,one-pad-char,url-one-byteandurl-two-bytes: a last group of 1 or 2 bytes, with and without padding.zero-bytes: the bytes00 00 00giveAAAA.plus-and-slash,minus-and-underscore,all-62-*andall-63-*: the bytesfb ffgive+/8=in standard and-_8in url. These cases catch a solution that uses the wrong alphabet.non-ascii-standardandnon-ascii-url: the UTF-8 bytes ofé€🙂.
The cases of decode are in cases/decode.jsonl. The toolchain does not load this file yet, so the test files hold its cases by name. The cases in cases/errors.jsonl must give the error invalid. The test files hold them by name too:
plus-in-url,minus-in-standard,bangandnon-ascii-char: characters outside the alphabet.space,line-feed,line-feed-urlandtrailing-crlf: white space and line breaks.missing-padding,missing-one-pad,excess-padding,padding-in-middle,three-pads,only-padding,padding-then-dataandpadding-in-url: a wrong padding.length-1-mod-4-standard,length-1-mod-4-urlandone-char-url: a length that is 1 mod 4.pad-bits-one-byte,pad-bits-two-bytesandpad-bits-url:QR==,Zm9=andZm9have non-zero pad bits.
Pitfalls
- Lenient decoders accept bad text.
Buffer.from(text, "base64")in Node.js accepts both alphabets and a missing padding, and it skips characters outside the alphabet. The documentation says thatbase64also accepts the URL-safe alphabet and ignores white space. No input gives an error:
This code runs but gives a wrong answer on purpose.
const texts = ["Zm9vYmFy", "Zm9v YmFy", "Zm9v!YmFy", "Zm9vYmF=", "-_8=", "+/8", "!!!!"];
for (const text of texts) {
console.log(JSON.stringify(text).padEnd(12), Buffer.from(text, "base64").toString("hex"));
}
"Zm9vYmFy" 666f6f626172
"Zm9v YmFy" 666f6f626172
"Zm9v!YmFy" 666f6f626172
"Zm9vYmF=" 666f6f6261
"-_8=" fbff
"+/8" fbff
"!!!!"
To be strict, encode the result again and compare it with the text, as the solutions do.
- Non-zero pad bits give the same bytes.
b64decodewithvalidate=Truerejects characters outside the alphabet, but it ignores the pad bits. So four texts decode to the same two bytes:
This code runs but gives a wrong answer on purpose.
import base64
for text in ["Zm8=", "Zm9=", "Zm+=", "Zm/="]:
print(text, base64.b64decode(text, validate=True))
Zm8= b'fo'
Zm9= b'fo'
Zm+= b'fo'
Zm/= b'fo'
Code that compares Base64 texts, for example as keys or signatures, then sees four different values for the same data.
- MIME text has line breaks. RFC 2045 limits a MIME line to 76 characters, and RFC 4648 section 3.1 forbids line feeds unless the referring specification asks for them. Java's MIME encoder adds
\r\nafter each 76 characters, and the basic decoder rejects the\r:
import java.util.Base64;
public class Main {
public static void main(String[] args) {
String mime = Base64.getMimeEncoder().encodeToString(new byte[60]);
System.out.println("length " + mime.length() + ", line break at " + mime.indexOf("\r\n"));
try {
Base64.getDecoder().decode(mime);
} catch (IllegalArgumentException e) {
System.out.println("getDecoder: " + e.getMessage());
}
System.out.println("getMimeDecoder: " + Base64.getMimeDecoder().decode(mime).length + " bytes");
}
}
length 82, line break at 76
getDecoder: Illegal base64 character d
getMimeDecoder: 60 bytes
GNU base64 wraps after 76 characters too. Give -w 0 to turn the wrap off, or remove the newlines as the Bash solution does.
- The standard decoder drops the URL-safe characters. Without
validate=True, Python'sb64decodediscards the characters outside the standard alphabet before it checks the padding. So it reads url text with no error and returns other bytes:
This code runs but gives a wrong answer on purpose.
import base64
text = base64.urlsafe_b64encode(bytes.fromhex("fbffbf") + b"foo").decode()
print(text)
print(base64.b64decode(text))
print(base64.urlsafe_b64decode(text))
-_-_Zm9v
b'foo'
b'\xfb\xff\xbffoo'
Decode with the alphabet that the text uses, and decode strictly.
- JWT parts have no padding. RFC 7515 removes the trailing
=. A decoder that requires the padding rejects such a part. In C#,Convert.FromBase64Stringthrows, andBase64Url.DecodeFromCharsdecodes it:
using System.Buffers.Text;
using System.Text;
string header = "eyJhbGciOiJub25lIn0";
try
{
Convert.FromBase64String(header);
}
catch (FormatException e)
{
Console.WriteLine("FromBase64String: " + e.GetType().Name);
}
Console.WriteLine("Base64Url: " + Encoding.UTF8.GetString(Base64Url.DecodeFromChars(header)));
FromBase64String: FormatException
Base64Url: {"alg":"none"}
- The bytes of a string depend on its encoding. In C#,
Encoding.Unicodeis UTF-16 in little-endian byte order, not UTF-8. The same string gives two different Base64 texts:
This code runs but gives a wrong answer on purpose.
using System.Text;
Console.WriteLine("Unicode: " + Convert.ToBase64String(Encoding.Unicode.GetBytes("hi")));
Console.WriteLine("UTF8: " + Convert.ToBase64String(Encoding.UTF8.GetBytes("hi")));
Unicode: aABpAA==
UTF8: aGk=
Use UTF-8, unless the other side of the exchange asks for another encoding.
btoatakes bytes, not text.btoareads each character of its argument as one byte. MDN says that it throwsInvalidCharacterErrorfor a character above U+00FF. Encode the text as UTF-8 first:
try {
btoa("€");
} catch (e) {
console.log("btoa:", e.name);
}
const bytes = new TextEncoder().encode("€");
console.log("UTF-8:", Buffer.from(bytes).toString("base64"));
btoa: InvalidCharacterError
UTF-8: 4oKs
Related tasks
- UTF-8: get the bytes of a string before you encode it.
- Compute a SHA-256 hash: a digest is bytes, and Base64 is one way to write it as text.
- Read and write JSON: a JSON string can carry bytes as Base64 text (see JSON).
- Read from standard input: the Bash solution reads the bytes on the standard input.
- Write a file: write the decoded bytes to a file.
- Deserialization of untrusted data: decoded bytes from an untrusted source are still untrusted.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/base64-encode-and-decode/.
import base64
def encode(data: bytes, alphabet: str = "standard") -> str:
"""Encode data as Base64 text.
The standard alphabet pads the text with "=". The url alphabet uses
"-" and "_" for "+" and "/" and adds no padding.
"""
if alphabet == "standard":
return base64.b64encode(data).decode("ascii")
if alphabet == "url":
return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
raise ValueError(f"unknown alphabet: {alphabet!r}")
def decode(text: str, alphabet: str = "standard") -> bytes:
"""Decode Base64 text strictly, and raise ValueError on bad input.
The text is valid only when it is exactly what encode gives for some
bytes: no white space, the right padding, and zero pad bits.
"""
if alphabet not in ("standard", "url"):
raise ValueError(f"unknown alphabet: {alphabet!r}")
try:
if alphabet == "url":
padded = text + "=" * (-len(text) % 4)
data = base64.b64decode(padded, altchars=b"-_", validate=True)
else:
data = base64.b64decode(text, validate=True)
except ValueError: # binascii.Error, or a non-ASCII character
raise ValueError(f"invalid base64 text: {text!r}") from None
# validate=True still accepts non-zero pad bits, and with altchars it
# also accepts "+" and "/". Only the canonical text encodes back to
# itself, so this check rejects both.
if encode(data, alphabet) != text:
raise ValueError(f"invalid base64 text: {text!r}")
return data
test_b64.py 103 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/base64-encode-and-decode/.
import pytest
from b64 import decode, encode
# The bytes are written in hexadecimal.
ENCODE = {
"rfc-f": ("66", "standard", "Zg=="),
"rfc-fo": ("666f", "standard", "Zm8="),
"rfc-foo": ("666f6f", "standard", "Zm9v"),
"rfc-foob": ("666f6f62", "standard", "Zm9vYg=="),
"rfc-fooba": ("666f6f6261", "standard", "Zm9vYmE="),
"rfc-foobar": ("666f6f626172", "standard", "Zm9vYmFy"),
"hello-standard": ("48656c6c6f2c20776f726c6421", "standard", "SGVsbG8sIHdvcmxkIQ=="),
"hello-url": ("48656c6c6f2c20776f726c6421", "url", "SGVsbG8sIHdvcmxkIQ"),
"empty-standard": ("", "standard", ""),
"empty-url": ("", "url", ""),
"two-pad-chars": ("00", "standard", "AA=="),
"one-pad-char": ("0000", "standard", "AAA="),
"zero-bytes": ("000000", "standard", "AAAA"),
"plus-and-slash": ("fbff", "standard", "+/8="),
"minus-and-underscore": ("fbff", "url", "-_8"),
"all-62-standard": ("fbefbe", "standard", "++++"),
"all-62-url": ("fbefbe", "url", "----"),
"all-63-standard": ("ffffff", "standard", "////"),
"all-63-url": ("ffffff", "url", "____"),
"url-one-byte": ("66", "url", "Zg"),
"url-two-bytes": ("666f", "url", "Zm8"),
"non-ascii-standard": ("c3a9e282acf09f9982", "standard", "w6nigqzwn5mC"),
"non-ascii-url": ("c3a9e282acf09f9982", "url", "w6nigqzwn5mC"),
}
DECODE = {
"rfc-empty": ("", "standard", ""),
"rfc-f": ("Zg==", "standard", "66"),
"rfc-fo": ("Zm8=", "standard", "666f"),
"rfc-foo": ("Zm9v", "standard", "666f6f"),
"rfc-foob": ("Zm9vYg==", "standard", "666f6f62"),
"rfc-fooba": ("Zm9vYmE=", "standard", "666f6f6261"),
"rfc-foobar": ("Zm9vYmFy", "standard", "666f6f626172"),
"empty-url": ("", "url", ""),
"url-foob": ("Zm9vYg", "url", "666f6f62"),
"url-fooba": ("Zm9vYmE", "url", "666f6f6261"),
"url-foobar": ("Zm9vYmFy", "url", "666f6f626172"),
"plus-and-slash": ("+/8=", "standard", "fbff"),
"minus-and-underscore": ("-_8", "url", "fbff"),
"all-63-url": ("____", "url", "ffffff"),
"zero-bytes": ("AAAA", "standard", "000000"),
"non-ascii-standard": ("w6nigqzwn5mC", "standard", "c3a9e282acf09f9982"),
"non-ascii-url": ("w6nigqzwn5mC", "url", "c3a9e282acf09f9982"),
}
ERRORS = {
"plus-in-url": ("+/8", "url"),
"minus-in-standard": ("-_8=", "standard"),
"bang": ("Zm9v!", "standard"),
"non-ascii-char": ("Zm9vé===", "standard"),
"space": ("Zm9v YmFy", "standard"),
"line-feed": ("Zm9v\nYmFy", "standard"),
"trailing-crlf": ("Zm9vYmFy\r\n", "standard"),
"line-feed-url": ("Zm9v\nYmFy", "url"),
"missing-padding": ("Zm8", "standard"),
"missing-one-pad": ("Zg=", "standard"),
"excess-padding": ("Zm9v=", "standard"),
"padding-in-middle": ("Zm=9", "standard"),
"three-pads": ("Z===", "standard"),
"only-padding": ("====", "standard"),
"padding-then-data": ("Zg==Zm8=", "standard"),
"padding-in-url": ("Zm8=", "url"),
"length-1-mod-4-standard": ("Zm9vY", "standard"),
"length-1-mod-4-url": ("Zm9vY", "url"),
"one-char-url": ("Z", "url"),
"pad-bits-one-byte": ("QR==", "standard"),
"pad-bits-two-bytes": ("Zm9=", "standard"),
"pad-bits-url": ("Zm9", "url"),
}
@pytest.mark.parametrize("name", ENCODE)
def test_encode(name):
data, alphabet, want = ENCODE[name]
assert encode(bytes.fromhex(data), alphabet) == want
@pytest.mark.parametrize("name", DECODE)
def test_decode(name):
text, alphabet, want = DECODE[name]
assert decode(text, alphabet).hex() == want
@pytest.mark.parametrize("name", ENCODE)
def test_round_trip(name):
data, alphabet, _ = ENCODE[name]
assert decode(encode(bytes.fromhex(data), alphabet), alphabet).hex() == data
@pytest.mark.parametrize("name", ERRORS)
def test_invalid(name):
text, alphabet = ERRORS[name]
with pytest.raises(ValueError):
decode(text, alphabet)
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/base64-encode-and-decode/.
#include "b64.hpp"
#include <algorithm>
#include <cstddef>
#include <stdexcept>
namespace b64 {
namespace {
constexpr std::string_view standard_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
constexpr std::string_view url_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
std::string_view chars_of(Alphabet alphabet) {
return alphabet == Alphabet::url ? url_chars : standard_chars;
}
[[noreturn]] void invalid(std::string_view text) {
throw std::invalid_argument("invalid base64 text: " + std::string(text));
}
} // namespace
std::string encode(std::span<const std::uint8_t> data, Alphabet alphabet) {
const std::string_view chars = chars_of(alphabet);
std::string text;
text.reserve((data.size() + 2) / 3 * 4);
for (std::size_t i = 0; i < data.size(); i += 3) {
const auto chunk = data.subspan(i, std::min<std::size_t>(3, data.size() - i));
// Put the 1 to 3 bytes in the top 24 bits of v, with zero bits after.
std::uint32_t v = 0;
for (std::size_t k = 0; k < 3; k++) {
v = (v << 8) | (k < chunk.size() ? chunk[k] : 0U);
}
for (std::size_t k = 0; k < 4; k++) {
if (k <= chunk.size()) {
text += chars[(v >> (18 - 6 * k)) & 63];
} else if (alphabet == Alphabet::standard) {
text += '=';
}
}
}
return text;
}
std::vector<std::uint8_t> decode(std::string_view text, Alphabet alphabet) {
const std::string_view chars = chars_of(alphabet);
std::string_view body = text;
if (alphabet == Alphabet::standard) {
if (body.size() % 4 != 0) {
invalid(text);
}
// Remove at most two '=' at the end. Any other '=' is not in the
// alphabet, so the loop below rejects it.
for (int k = 0; k < 2 && body.ends_with('='); k++) {
body.remove_suffix(1);
}
}
if (body.size() % 4 == 1) {
invalid(text);
}
std::vector<std::uint8_t> data;
data.reserve(body.size() / 4 * 3 + 2);
for (std::size_t i = 0; i < body.size(); i += 4) {
const std::string_view group = body.substr(i, 4);
std::uint32_t v = 0;
for (const char c : group) {
const std::size_t value = chars.find(c);
if (value == std::string_view::npos) {
invalid(text);
}
v = (v << 6) | static_cast<std::uint32_t>(value);
}
// 4, 3 or 2 characters hold 3, 2 or 1 bytes and 0, 2 or 4 pad bits.
const std::size_t bytes = group.size() * 6 / 8;
const std::size_t pad_bits = group.size() * 6 - bytes * 8;
if ((v & ((1U << pad_bits) - 1)) != 0) {
invalid(text);
}
v >>= pad_bits;
for (std::size_t k = bytes; k-- > 0;) {
data.push_back(static_cast<std::uint8_t>(v >> (8 * k)));
}
}
return data;
}
} // namespace b64
b64.hpp 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/base64-encode-and-decode/.
#pragma once
#include <cstdint>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace b64 {
// standard is RFC 4648 section 4, padded with '='. url is section 5, with no
// padding.
enum class Alphabet { standard, url };
// Returns the Base64 text of data.
std::string encode(std::span<const std::uint8_t> data, Alphabet alphabet);
// Returns the bytes of text. Throws std::invalid_argument when text is not
// exactly what encode gives for some bytes.
std::vector<std::uint8_t> decode(std::string_view text, Alphabet alphabet);
} // namespace b64
test_b64.cpp 141 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/base64-encode-and-decode/.
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
#include "b64.hpp"
namespace {
int failures = 0;
void fail(std::string_view name) {
std::fprintf(stderr, "case %.*s failed\n", static_cast<int>(name.size()), name.data());
failures++;
}
b64::Alphabet alphabet(std::string_view name) {
return name == "url" ? b64::Alphabet::url : b64::Alphabet::standard;
}
std::vector<std::uint8_t> from_hex(std::string_view hex) {
std::vector<std::uint8_t> data;
for (std::size_t i = 0; i + 1 < hex.size(); i += 2) {
data.push_back(static_cast<std::uint8_t>(std::stoi(std::string(hex.substr(i, 2)), nullptr, 16)));
}
return data;
}
void check_encode(std::string_view name, std::string_view hex, std::string_view a,
std::string_view want) {
const auto data = from_hex(hex);
const std::string text = b64::encode(data, alphabet(a));
if (text != want) {
fail(name);
return;
}
try {
if (b64::decode(text, alphabet(a)) != data) {
fail(name);
}
} catch (const std::invalid_argument &) {
fail(name);
}
}
void check_decode(std::string_view name, std::string_view text, std::string_view a,
std::string_view want) {
try {
if (b64::decode(text, alphabet(a)) != from_hex(want)) {
fail(name);
}
} catch (const std::invalid_argument &) {
fail(name);
}
}
void check_invalid(std::string_view name, std::string_view text, std::string_view a) {
try {
b64::decode(text, alphabet(a));
fail(name);
} catch (const std::invalid_argument &) {
}
}
} // namespace
int main() {
// The bytes are written in hexadecimal.
check_encode("rfc-f", "66", "standard", "Zg==");
check_encode("rfc-fo", "666f", "standard", "Zm8=");
check_encode("rfc-foo", "666f6f", "standard", "Zm9v");
check_encode("rfc-foob", "666f6f62", "standard", "Zm9vYg==");
check_encode("rfc-fooba", "666f6f6261", "standard", "Zm9vYmE=");
check_encode("rfc-foobar", "666f6f626172", "standard", "Zm9vYmFy");
check_encode("hello-standard", "48656c6c6f2c20776f726c6421", "standard", "SGVsbG8sIHdvcmxkIQ==");
check_encode("hello-url", "48656c6c6f2c20776f726c6421", "url", "SGVsbG8sIHdvcmxkIQ");
check_encode("empty-standard", "", "standard", "");
check_encode("empty-url", "", "url", "");
check_encode("two-pad-chars", "00", "standard", "AA==");
check_encode("one-pad-char", "0000", "standard", "AAA=");
check_encode("zero-bytes", "000000", "standard", "AAAA");
check_encode("plus-and-slash", "fbff", "standard", "+/8=");
check_encode("minus-and-underscore", "fbff", "url", "-_8");
check_encode("all-62-standard", "fbefbe", "standard", "++++");
check_encode("all-62-url", "fbefbe", "url", "----");
check_encode("all-63-standard", "ffffff", "standard", "////");
check_encode("all-63-url", "ffffff", "url", "____");
check_encode("url-one-byte", "66", "url", "Zg");
check_encode("url-two-bytes", "666f", "url", "Zm8");
check_encode("non-ascii-standard", "c3a9e282acf09f9982", "standard", "w6nigqzwn5mC");
check_encode("non-ascii-url", "c3a9e282acf09f9982", "url", "w6nigqzwn5mC");
check_decode("rfc-empty", "", "standard", "");
check_decode("rfc-f", "Zg==", "standard", "66");
check_decode("rfc-fo", "Zm8=", "standard", "666f");
check_decode("rfc-foo", "Zm9v", "standard", "666f6f");
check_decode("rfc-foob", "Zm9vYg==", "standard", "666f6f62");
check_decode("rfc-fooba", "Zm9vYmE=", "standard", "666f6f6261");
check_decode("rfc-foobar", "Zm9vYmFy", "standard", "666f6f626172");
check_decode("empty-url", "", "url", "");
check_decode("url-foob", "Zm9vYg", "url", "666f6f62");
check_decode("url-fooba", "Zm9vYmE", "url", "666f6f6261");
check_decode("url-foobar", "Zm9vYmFy", "url", "666f6f626172");
check_decode("plus-and-slash", "+/8=", "standard", "fbff");
check_decode("minus-and-underscore", "-_8", "url", "fbff");
check_decode("all-63-url", "____", "url", "ffffff");
check_decode("zero-bytes", "AAAA", "standard", "000000");
check_decode("non-ascii-standard", "w6nigqzwn5mC", "standard", "c3a9e282acf09f9982");
check_decode("non-ascii-url", "w6nigqzwn5mC", "url", "c3a9e282acf09f9982");
check_invalid("plus-in-url", "+/8", "url");
check_invalid("minus-in-standard", "-_8=", "standard");
check_invalid("bang", "Zm9v!", "standard");
check_invalid("non-ascii-char", "Zm9vé===", "standard");
check_invalid("space", "Zm9v YmFy", "standard");
check_invalid("line-feed", "Zm9v\nYmFy", "standard");
check_invalid("trailing-crlf", "Zm9vYmFy\r\n", "standard");
check_invalid("line-feed-url", "Zm9v\nYmFy", "url");
check_invalid("missing-padding", "Zm8", "standard");
check_invalid("missing-one-pad", "Zg=", "standard");
check_invalid("excess-padding", "Zm9v=", "standard");
check_invalid("padding-in-middle", "Zm=9", "standard");
check_invalid("three-pads", "Z===", "standard");
check_invalid("only-padding", "====", "standard");
check_invalid("padding-then-data", "Zg==Zm8=", "standard");
check_invalid("padding-in-url", "Zm8=", "url");
check_invalid("length-1-mod-4-standard", "Zm9vY", "standard");
check_invalid("length-1-mod-4-url", "Zm9vY", "url");
check_invalid("one-char-url", "Z", "url");
check_invalid("pad-bits-one-byte", "QR==", "standard");
check_invalid("pad-bits-two-bytes", "Zm9=", "standard");
check_invalid("pad-bits-url", "Zm9", "url");
return failures == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/base64-encode-and-decode/.
import java.util.Base64;
/** Encodes bytes as Base64 text and decodes the text strictly. */
public final class Base64Codec {
/** STANDARD is RFC 4648 section 4 with padding; URL is section 5 with no padding. */
public enum Alphabet {
STANDARD,
URL
}
private Base64Codec() {}
public static String encode(byte[] data, Alphabet alphabet) {
return switch (alphabet) {
case STANDARD -> Base64.getEncoder().encodeToString(data);
case URL -> Base64.getUrlEncoder().withoutPadding().encodeToString(data);
};
}
/** Decodes text, and throws IllegalArgumentException when it is not valid. */
public static byte[] decode(String text, Alphabet alphabet) {
byte[] data;
try {
data =
switch (alphabet) {
case STANDARD -> Base64.getDecoder().decode(text);
case URL -> Base64.getUrlDecoder().decode(text);
};
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("invalid base64 text: " + text, e);
}
// The decoders accept a missing padding and non-zero pad bits. Only the
// canonical text encodes back to itself, so this check rejects them.
if (!encode(data, alphabet).equals(text)) {
throw new IllegalArgumentException("invalid base64 text: " + text);
}
return data;
}
}
Base64CodecTest.java 121 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/base64-encode-and-decode/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.HexFormat;
import java.util.Locale;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class Base64CodecTest {
private static final HexFormat HEX = HexFormat.of();
private static Base64Codec.Alphabet alphabet(String name) {
return Base64Codec.Alphabet.valueOf(name.toUpperCase(Locale.ROOT));
}
// The bytes are written in hexadecimal.
static Stream<Arguments> encodeCases() {
return Stream.of(
Arguments.of("rfc-f", "66", "standard", "Zg=="),
Arguments.of("rfc-fo", "666f", "standard", "Zm8="),
Arguments.of("rfc-foo", "666f6f", "standard", "Zm9v"),
Arguments.of("rfc-foob", "666f6f62", "standard", "Zm9vYg=="),
Arguments.of("rfc-fooba", "666f6f6261", "standard", "Zm9vYmE="),
Arguments.of("rfc-foobar", "666f6f626172", "standard", "Zm9vYmFy"),
Arguments.of("hello-standard", "48656c6c6f2c20776f726c6421", "standard", "SGVsbG8sIHdvcmxkIQ=="),
Arguments.of("hello-url", "48656c6c6f2c20776f726c6421", "url", "SGVsbG8sIHdvcmxkIQ"),
Arguments.of("empty-standard", "", "standard", ""),
Arguments.of("empty-url", "", "url", ""),
Arguments.of("two-pad-chars", "00", "standard", "AA=="),
Arguments.of("one-pad-char", "0000", "standard", "AAA="),
Arguments.of("zero-bytes", "000000", "standard", "AAAA"),
Arguments.of("plus-and-slash", "fbff", "standard", "+/8="),
Arguments.of("minus-and-underscore", "fbff", "url", "-_8"),
Arguments.of("all-62-standard", "fbefbe", "standard", "++++"),
Arguments.of("all-62-url", "fbefbe", "url", "----"),
Arguments.of("all-63-standard", "ffffff", "standard", "////"),
Arguments.of("all-63-url", "ffffff", "url", "____"),
Arguments.of("url-one-byte", "66", "url", "Zg"),
Arguments.of("url-two-bytes", "666f", "url", "Zm8"),
Arguments.of("non-ascii-standard", "c3a9e282acf09f9982", "standard", "w6nigqzwn5mC"),
Arguments.of("non-ascii-url", "c3a9e282acf09f9982", "url", "w6nigqzwn5mC"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("encodeCases")
void encode(String name, String data, String alphabet, String want) {
assertEquals(want, Base64Codec.encode(HEX.parseHex(data), alphabet(alphabet)));
}
@ParameterizedTest(name = "{0}")
@MethodSource("encodeCases")
void roundTrip(String name, String data, String alphabet, String want) {
String text = Base64Codec.encode(HEX.parseHex(data), alphabet(alphabet));
assertEquals(data, HEX.formatHex(Base64Codec.decode(text, alphabet(alphabet))));
}
static Stream<Arguments> decodeCases() {
return Stream.of(
Arguments.of("rfc-empty", "", "standard", ""),
Arguments.of("rfc-f", "Zg==", "standard", "66"),
Arguments.of("rfc-fo", "Zm8=", "standard", "666f"),
Arguments.of("rfc-foo", "Zm9v", "standard", "666f6f"),
Arguments.of("rfc-foob", "Zm9vYg==", "standard", "666f6f62"),
Arguments.of("rfc-fooba", "Zm9vYmE=", "standard", "666f6f6261"),
Arguments.of("rfc-foobar", "Zm9vYmFy", "standard", "666f6f626172"),
Arguments.of("empty-url", "", "url", ""),
Arguments.of("url-foob", "Zm9vYg", "url", "666f6f62"),
Arguments.of("url-fooba", "Zm9vYmE", "url", "666f6f6261"),
Arguments.of("url-foobar", "Zm9vYmFy", "url", "666f6f626172"),
Arguments.of("plus-and-slash", "+/8=", "standard", "fbff"),
Arguments.of("minus-and-underscore", "-_8", "url", "fbff"),
Arguments.of("all-63-url", "____", "url", "ffffff"),
Arguments.of("zero-bytes", "AAAA", "standard", "000000"),
Arguments.of("non-ascii-standard", "w6nigqzwn5mC", "standard", "c3a9e282acf09f9982"),
Arguments.of("non-ascii-url", "w6nigqzwn5mC", "url", "c3a9e282acf09f9982"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("decodeCases")
void decode(String name, String text, String alphabet, String want) {
assertEquals(want, HEX.formatHex(Base64Codec.decode(text, alphabet(alphabet))));
}
static Stream<Arguments> errorCases() {
return Stream.of(
Arguments.of("plus-in-url", "+/8", "url"),
Arguments.of("minus-in-standard", "-_8=", "standard"),
Arguments.of("bang", "Zm9v!", "standard"),
Arguments.of("non-ascii-char", "Zm9vé===", "standard"),
Arguments.of("space", "Zm9v YmFy", "standard"),
Arguments.of("line-feed", "Zm9v\nYmFy", "standard"),
Arguments.of("trailing-crlf", "Zm9vYmFy\r\n", "standard"),
Arguments.of("line-feed-url", "Zm9v\nYmFy", "url"),
Arguments.of("missing-padding", "Zm8", "standard"),
Arguments.of("missing-one-pad", "Zg=", "standard"),
Arguments.of("excess-padding", "Zm9v=", "standard"),
Arguments.of("padding-in-middle", "Zm=9", "standard"),
Arguments.of("three-pads", "Z===", "standard"),
Arguments.of("only-padding", "====", "standard"),
Arguments.of("padding-then-data", "Zg==Zm8=", "standard"),
Arguments.of("padding-in-url", "Zm8=", "url"),
Arguments.of("length-1-mod-4-standard", "Zm9vY", "standard"),
Arguments.of("length-1-mod-4-url", "Zm9vY", "url"),
Arguments.of("one-char-url", "Z", "url"),
Arguments.of("pad-bits-one-byte", "QR==", "standard"),
Arguments.of("pad-bits-two-bytes", "Zm9=", "standard"),
Arguments.of("pad-bits-url", "Zm9", "url"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("errorCases")
void invalid(String name, String text, String alphabet) {
assertThrows(
IllegalArgumentException.class, () -> Base64Codec.decode(text, alphabet(alphabet)));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/base64-encode-and-decode/.
#include "b64.h"
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
static const char STANDARD[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static const char URL[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
char *b64_encode(const unsigned char *data, size_t len, enum b64_alphabet alphabet) {
const char *chars = alphabet == B64_URL ? URL : STANDARD;
// Each group of 3 bytes gives 4 characters. Check that the size fits.
if (len / 3 >= (SIZE_MAX - 5) / 4) {
return NULL;
}
char *text = malloc(len / 3 * 4 + 5);
if (text == NULL) {
return NULL;
}
char *p = text;
for (size_t i = 0; i < len; i += 3) {
size_t n = len - i < 3 ? len - i : 3;
// Put the 1 to 3 bytes in the top 24 bits of v, with zero bits after.
uint32_t v = (uint32_t)data[i] << 16;
if (n > 1) {
v |= (uint32_t)data[i + 1] << 8;
}
if (n > 2) {
v |= data[i + 2];
}
for (size_t k = 0; k < 4; k++) {
if (k <= n) {
*p++ = chars[(v >> (18 - 6 * k)) & 63];
} else if (alphabet == B64_STANDARD) {
*p++ = '=';
}
}
}
*p = '\0';
return text;
}
enum b64_status b64_decode(const char *text, enum b64_alphabet alphabet, unsigned char **data,
size_t *len) {
const char *chars = alphabet == B64_URL ? URL : STANDARD;
size_t n = strlen(text);
if (alphabet == B64_STANDARD) {
if (n % 4 != 0) {
return B64_INVALID;
}
// Remove at most two '=' at the end. Any other '=' is not in the
// alphabet, so the loop below rejects it.
for (int k = 0; k < 2 && n > 0 && text[n - 1] == '='; k++) {
n--;
}
}
if (n % 4 == 1) {
return B64_INVALID;
}
unsigned char *out = malloc(n / 4 * 3 + 3);
if (out == NULL) {
return B64_NO_MEMORY;
}
size_t m = 0;
for (size_t i = 0; i < n; i += 4) {
size_t count = n - i < 4 ? n - i : 4;
uint32_t v = 0;
for (size_t k = 0; k < count; k++) {
const char *c = memchr(chars, text[i + k], 64);
if (c == NULL) {
free(out);
return B64_INVALID;
}
v = (v << 6) | (uint32_t)(c - chars);
}
// 4, 3 or 2 characters hold 3, 2 or 1 bytes and 0, 2 or 4 pad bits.
size_t bytes = count * 6 / 8;
size_t pad_bits = count * 6 - bytes * 8;
if ((v & ((UINT32_C(1) << pad_bits) - 1)) != 0) {
free(out);
return B64_INVALID;
}
v >>= pad_bits;
for (size_t k = bytes; k-- > 0;) {
out[m++] = (unsigned char)(v >> (8 * k));
}
}
*data = out;
*len = m;
return B64_OK;
}
b64.h 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/base64-encode-and-decode/.
#ifndef B64_H
#define B64_H
#include <stddef.h>
// B64_STANDARD is RFC 4648 section 4, padded with '='. B64_URL is section 5,
// with no padding.
enum b64_alphabet { B64_STANDARD, B64_URL };
enum b64_status { B64_OK, B64_INVALID, B64_NO_MEMORY };
// Returns the Base64 text of the len bytes at data as a new string, or NULL
// when there is no memory. The caller frees the string.
char *b64_encode(const unsigned char *data, size_t len, enum b64_alphabet alphabet);
// Decodes text, which must be exactly what b64_encode gives for some bytes.
// On B64_OK, *data is a new buffer of *len bytes that the caller frees. On an
// error, *data and *len do not change.
enum b64_status b64_decode(const char *text, enum b64_alphabet alphabet, unsigned char **data,
size_t *len);
#endif
test_b64.c 142 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/base64-encode-and-decode/.
#include "b64.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int failures = 0;
static void fail(const char *name) {
fprintf(stderr, "case %s failed\n", name);
failures++;
}
static enum b64_alphabet alphabet(const char *name) {
return strcmp(name, "url") == 0 ? B64_URL : B64_STANDARD;
}
// Writes the bytes of hex to out and returns their count.
static size_t from_hex(const char *hex, unsigned char *out) {
size_t n = strlen(hex) / 2;
for (size_t i = 0; i < n; i++) {
unsigned int b = 0;
sscanf(hex + 2 * i, "%2x", &b);
out[i] = (unsigned char)b;
}
return n;
}
// Checks that the len bytes at data are the bytes of hex.
static int same(const unsigned char *data, size_t len, const char *hex) {
unsigned char want[64];
return len == from_hex(hex, want) && (len == 0 || memcmp(data, want, len) == 0);
}
static void check_encode(const char *name, const char *hex, const char *a, const char *want) {
unsigned char data[64];
size_t len = from_hex(hex, data);
char *text = b64_encode(data, len, alphabet(a));
if (text == NULL || strcmp(text, want) != 0) {
fail(name);
free(text);
return;
}
unsigned char *back = NULL;
size_t back_len = 0;
if (b64_decode(text, alphabet(a), &back, &back_len) != B64_OK || !same(back, back_len, hex)) {
fail(name);
}
free(back);
free(text);
}
static void check_decode(const char *name, const char *text, const char *a, const char *want) {
unsigned char *data = NULL;
size_t len = 0;
if (b64_decode(text, alphabet(a), &data, &len) != B64_OK || !same(data, len, want)) {
fail(name);
}
free(data);
}
static void check_invalid(const char *name, const char *text, const char *a) {
unsigned char *data = NULL;
size_t len = 0;
if (b64_decode(text, alphabet(a), &data, &len) != B64_INVALID || data != NULL) {
fail(name);
}
free(data);
}
int main(void) {
// The bytes are written in hexadecimal.
check_encode("rfc-f", "66", "standard", "Zg==");
check_encode("rfc-fo", "666f", "standard", "Zm8=");
check_encode("rfc-foo", "666f6f", "standard", "Zm9v");
check_encode("rfc-foob", "666f6f62", "standard", "Zm9vYg==");
check_encode("rfc-fooba", "666f6f6261", "standard", "Zm9vYmE=");
check_encode("rfc-foobar", "666f6f626172", "standard", "Zm9vYmFy");
check_encode("hello-standard", "48656c6c6f2c20776f726c6421", "standard", "SGVsbG8sIHdvcmxkIQ==");
check_encode("hello-url", "48656c6c6f2c20776f726c6421", "url", "SGVsbG8sIHdvcmxkIQ");
check_encode("empty-standard", "", "standard", "");
check_encode("empty-url", "", "url", "");
check_encode("two-pad-chars", "00", "standard", "AA==");
check_encode("one-pad-char", "0000", "standard", "AAA=");
check_encode("zero-bytes", "000000", "standard", "AAAA");
check_encode("plus-and-slash", "fbff", "standard", "+/8=");
check_encode("minus-and-underscore", "fbff", "url", "-_8");
check_encode("all-62-standard", "fbefbe", "standard", "++++");
check_encode("all-62-url", "fbefbe", "url", "----");
check_encode("all-63-standard", "ffffff", "standard", "////");
check_encode("all-63-url", "ffffff", "url", "____");
check_encode("url-one-byte", "66", "url", "Zg");
check_encode("url-two-bytes", "666f", "url", "Zm8");
check_encode("non-ascii-standard", "c3a9e282acf09f9982", "standard", "w6nigqzwn5mC");
check_encode("non-ascii-url", "c3a9e282acf09f9982", "url", "w6nigqzwn5mC");
check_decode("rfc-empty", "", "standard", "");
check_decode("rfc-f", "Zg==", "standard", "66");
check_decode("rfc-fo", "Zm8=", "standard", "666f");
check_decode("rfc-foo", "Zm9v", "standard", "666f6f");
check_decode("rfc-foob", "Zm9vYg==", "standard", "666f6f62");
check_decode("rfc-fooba", "Zm9vYmE=", "standard", "666f6f6261");
check_decode("rfc-foobar", "Zm9vYmFy", "standard", "666f6f626172");
check_decode("empty-url", "", "url", "");
check_decode("url-foob", "Zm9vYg", "url", "666f6f62");
check_decode("url-fooba", "Zm9vYmE", "url", "666f6f6261");
check_decode("url-foobar", "Zm9vYmFy", "url", "666f6f626172");
check_decode("plus-and-slash", "+/8=", "standard", "fbff");
check_decode("minus-and-underscore", "-_8", "url", "fbff");
check_decode("all-63-url", "____", "url", "ffffff");
check_decode("zero-bytes", "AAAA", "standard", "000000");
check_decode("non-ascii-standard", "w6nigqzwn5mC", "standard", "c3a9e282acf09f9982");
check_decode("non-ascii-url", "w6nigqzwn5mC", "url", "c3a9e282acf09f9982");
check_invalid("plus-in-url", "+/8", "url");
check_invalid("minus-in-standard", "-_8=", "standard");
check_invalid("bang", "Zm9v!", "standard");
check_invalid("non-ascii-char", "Zm9vé===", "standard");
check_invalid("space", "Zm9v YmFy", "standard");
check_invalid("line-feed", "Zm9v\nYmFy", "standard");
check_invalid("trailing-crlf", "Zm9vYmFy\r\n", "standard");
check_invalid("line-feed-url", "Zm9v\nYmFy", "url");
check_invalid("missing-padding", "Zm8", "standard");
check_invalid("missing-one-pad", "Zg=", "standard");
check_invalid("excess-padding", "Zm9v=", "standard");
check_invalid("padding-in-middle", "Zm=9", "standard");
check_invalid("three-pads", "Z===", "standard");
check_invalid("only-padding", "====", "standard");
check_invalid("padding-then-data", "Zg==Zm8=", "standard");
check_invalid("padding-in-url", "Zm8=", "url");
check_invalid("length-1-mod-4-standard", "Zm9vY", "standard");
check_invalid("length-1-mod-4-url", "Zm9vY", "url");
check_invalid("one-char-url", "Z", "url");
check_invalid("pad-bits-one-byte", "QR==", "standard");
check_invalid("pad-bits-two-bytes", "Zm9=", "standard");
check_invalid("pad-bits-url", "Zm9", "url");
return failures == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/base64-encode-and-decode/.
using System.Buffers.Text;
/// <summary>Standard is RFC 4648 section 4 with padding; Url is section 5 with no padding.</summary>
public enum Base64Alphabet
{
Standard,
Url,
}
/// <summary>Encodes bytes as Base64 text and decodes the text strictly.</summary>
public static class Base64Codec
{
public static string Encode(byte[] data, Base64Alphabet alphabet) => alphabet switch
{
Base64Alphabet.Standard => Convert.ToBase64String(data),
Base64Alphabet.Url => Base64Url.EncodeToString(data),
_ => throw new ArgumentOutOfRangeException(nameof(alphabet)),
};
/// <summary>Decodes text, and throws a FormatException when it is not valid.</summary>
public static byte[] Decode(string text, Base64Alphabet alphabet)
{
byte[] data;
try
{
data = alphabet switch
{
Base64Alphabet.Standard => Convert.FromBase64String(text),
Base64Alphabet.Url => Base64Url.DecodeFromChars(text),
_ => throw new ArgumentOutOfRangeException(nameof(alphabet)),
};
}
catch (FormatException e)
{
throw new FormatException($"invalid base64 text: {text}", e);
}
// Both decoders skip white space, and FromBase64String accepts
// non-zero pad bits. Only the canonical text encodes back to itself,
// so this check rejects them.
if (Encode(data, alphabet) != text)
{
throw new FormatException($"invalid base64 text: {text}");
}
return data;
}
}
Base64CodecTests.cs 120 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/base64-encode-and-decode/.
using Xunit;
public sealed class Base64CodecTests
{
private static Base64Alphabet Alphabet(string name) =>
name == "url" ? Base64Alphabet.Url : Base64Alphabet.Standard;
// The bytes are written in hexadecimal.
public static TheoryData<string, string, string, string> EncodeCases => new()
{
{ "rfc-f", "66", "standard", "Zg==" },
{ "rfc-fo", "666f", "standard", "Zm8=" },
{ "rfc-foo", "666f6f", "standard", "Zm9v" },
{ "rfc-foob", "666f6f62", "standard", "Zm9vYg==" },
{ "rfc-fooba", "666f6f6261", "standard", "Zm9vYmE=" },
{ "rfc-foobar", "666f6f626172", "standard", "Zm9vYmFy" },
{ "hello-standard", "48656c6c6f2c20776f726c6421", "standard", "SGVsbG8sIHdvcmxkIQ==" },
{ "hello-url", "48656c6c6f2c20776f726c6421", "url", "SGVsbG8sIHdvcmxkIQ" },
{ "empty-standard", "", "standard", "" },
{ "empty-url", "", "url", "" },
{ "two-pad-chars", "00", "standard", "AA==" },
{ "one-pad-char", "0000", "standard", "AAA=" },
{ "zero-bytes", "000000", "standard", "AAAA" },
{ "plus-and-slash", "fbff", "standard", "+/8=" },
{ "minus-and-underscore", "fbff", "url", "-_8" },
{ "all-62-standard", "fbefbe", "standard", "++++" },
{ "all-62-url", "fbefbe", "url", "----" },
{ "all-63-standard", "ffffff", "standard", "////" },
{ "all-63-url", "ffffff", "url", "____" },
{ "url-one-byte", "66", "url", "Zg" },
{ "url-two-bytes", "666f", "url", "Zm8" },
{ "non-ascii-standard", "c3a9e282acf09f9982", "standard", "w6nigqzwn5mC" },
{ "non-ascii-url", "c3a9e282acf09f9982", "url", "w6nigqzwn5mC" },
};
public static TheoryData<string, string, string, string> DecodeCases => new()
{
{ "rfc-empty", "", "standard", "" },
{ "rfc-f", "Zg==", "standard", "66" },
{ "rfc-fo", "Zm8=", "standard", "666f" },
{ "rfc-foo", "Zm9v", "standard", "666f6f" },
{ "rfc-foob", "Zm9vYg==", "standard", "666f6f62" },
{ "rfc-fooba", "Zm9vYmE=", "standard", "666f6f6261" },
{ "rfc-foobar", "Zm9vYmFy", "standard", "666f6f626172" },
{ "empty-url", "", "url", "" },
{ "url-foob", "Zm9vYg", "url", "666f6f62" },
{ "url-fooba", "Zm9vYmE", "url", "666f6f6261" },
{ "url-foobar", "Zm9vYmFy", "url", "666f6f626172" },
{ "plus-and-slash", "+/8=", "standard", "fbff" },
{ "minus-and-underscore", "-_8", "url", "fbff" },
{ "all-63-url", "____", "url", "ffffff" },
{ "zero-bytes", "AAAA", "standard", "000000" },
{ "non-ascii-standard", "w6nigqzwn5mC", "standard", "c3a9e282acf09f9982" },
{ "non-ascii-url", "w6nigqzwn5mC", "url", "c3a9e282acf09f9982" },
};
public static TheoryData<string, string, string> ErrorCases => new()
{
{ "plus-in-url", "+/8", "url" },
{ "minus-in-standard", "-_8=", "standard" },
{ "bang", "Zm9v!", "standard" },
{ "non-ascii-char", "Zm9vé===", "standard" },
{ "space", "Zm9v YmFy", "standard" },
{ "line-feed", "Zm9v\nYmFy", "standard" },
{ "trailing-crlf", "Zm9vYmFy\r\n", "standard" },
{ "line-feed-url", "Zm9v\nYmFy", "url" },
{ "missing-padding", "Zm8", "standard" },
{ "missing-one-pad", "Zg=", "standard" },
{ "excess-padding", "Zm9v=", "standard" },
{ "padding-in-middle", "Zm=9", "standard" },
{ "three-pads", "Z===", "standard" },
{ "only-padding", "====", "standard" },
{ "padding-then-data", "Zg==Zm8=", "standard" },
{ "padding-in-url", "Zm8=", "url" },
{ "length-1-mod-4-standard", "Zm9vY", "standard" },
{ "length-1-mod-4-url", "Zm9vY", "url" },
{ "one-char-url", "Z", "url" },
{ "pad-bits-one-byte", "QR==", "standard" },
{ "pad-bits-two-bytes", "Zm9=", "standard" },
{ "pad-bits-url", "Zm9", "url" },
};
[Theory]
[MemberData(nameof(EncodeCases))]
public void Encode(string name, string data, string alphabet, string want)
{
Assert.NotNull(name);
Assert.Equal(want, Base64Codec.Encode(Convert.FromHexString(data), Alphabet(alphabet)));
}
[Theory]
[MemberData(nameof(EncodeCases))]
public void RoundTrip(string name, string data, string alphabet, string want)
{
Assert.NotNull(name);
Assert.NotNull(want);
var bytes = Convert.FromHexString(data);
var text = Base64Codec.Encode(bytes, Alphabet(alphabet));
Assert.Equal(bytes, Base64Codec.Decode(text, Alphabet(alphabet)));
}
[Theory]
[MemberData(nameof(DecodeCases))]
public void Decode(string name, string text, string alphabet, string want)
{
Assert.NotNull(name);
Assert.Equal(want, Convert.ToHexStringLower(Base64Codec.Decode(text, Alphabet(alphabet))));
}
[Theory]
[MemberData(nameof(ErrorCases))]
public void Invalid(string name, string text, string alphabet)
{
Assert.NotNull(name);
Assert.Throws<FormatException>(() => Base64Codec.Decode(text, Alphabet(alphabet)));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/base64-encode-and-decode/.
import { Buffer } from "node:buffer";
// The Buffer encoding names: "base64" pads with "=", and "base64url"
// adds no padding.
function bufferEncoding(alphabet) {
if (alphabet === "standard") return "base64";
if (alphabet === "url") return "base64url";
throw new RangeError(`unknown alphabet: ${alphabet}`);
}
/** Encodes the bytes of a Uint8Array as Base64 text. */
export function encode(data, alphabet = "standard") {
const buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
return buf.toString(bufferEncoding(alphabet));
}
/** Decodes Base64 text strictly, and throws a SyntaxError on bad input. */
export function decode(text, alphabet = "standard") {
const encoding = bufferEncoding(alphabet);
// Buffer.from skips characters outside the alphabet, accepts both
// alphabets and does not need the padding. Only the canonical text
// encodes back to itself, so this check rejects everything else.
const data = Buffer.from(text, encoding);
if (data.toString(encoding) !== text) {
throw new SyntaxError(`invalid base64 text: ${JSON.stringify(text)}`);
}
return new Uint8Array(data);
}
b64.test.js 104 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/base64-encode-and-decode/.
import assert from "node:assert/strict";
import { Buffer } from "node:buffer";
import { test } from "node:test";
import { decode, encode } from "./b64.js";
// The bytes are written in hexadecimal.
const encodeCases = [
["rfc-f", "66", "standard", "Zg=="],
["rfc-fo", "666f", "standard", "Zm8="],
["rfc-foo", "666f6f", "standard", "Zm9v"],
["rfc-foob", "666f6f62", "standard", "Zm9vYg=="],
["rfc-fooba", "666f6f6261", "standard", "Zm9vYmE="],
["rfc-foobar", "666f6f626172", "standard", "Zm9vYmFy"],
["hello-standard", "48656c6c6f2c20776f726c6421", "standard", "SGVsbG8sIHdvcmxkIQ=="],
["hello-url", "48656c6c6f2c20776f726c6421", "url", "SGVsbG8sIHdvcmxkIQ"],
["empty-standard", "", "standard", ""],
["empty-url", "", "url", ""],
["two-pad-chars", "00", "standard", "AA=="],
["one-pad-char", "0000", "standard", "AAA="],
["zero-bytes", "000000", "standard", "AAAA"],
["plus-and-slash", "fbff", "standard", "+/8="],
["minus-and-underscore", "fbff", "url", "-_8"],
["all-62-standard", "fbefbe", "standard", "++++"],
["all-62-url", "fbefbe", "url", "----"],
["all-63-standard", "ffffff", "standard", "////"],
["all-63-url", "ffffff", "url", "____"],
["url-one-byte", "66", "url", "Zg"],
["url-two-bytes", "666f", "url", "Zm8"],
["non-ascii-standard", "c3a9e282acf09f9982", "standard", "w6nigqzwn5mC"],
["non-ascii-url", "c3a9e282acf09f9982", "url", "w6nigqzwn5mC"],
];
const decodeCases = [
["rfc-empty", "", "standard", ""],
["rfc-f", "Zg==", "standard", "66"],
["rfc-fo", "Zm8=", "standard", "666f"],
["rfc-foo", "Zm9v", "standard", "666f6f"],
["rfc-foob", "Zm9vYg==", "standard", "666f6f62"],
["rfc-fooba", "Zm9vYmE=", "standard", "666f6f6261"],
["rfc-foobar", "Zm9vYmFy", "standard", "666f6f626172"],
["empty-url", "", "url", ""],
["url-foob", "Zm9vYg", "url", "666f6f62"],
["url-fooba", "Zm9vYmE", "url", "666f6f6261"],
["url-foobar", "Zm9vYmFy", "url", "666f6f626172"],
["plus-and-slash", "+/8=", "standard", "fbff"],
["minus-and-underscore", "-_8", "url", "fbff"],
["all-63-url", "____", "url", "ffffff"],
["zero-bytes", "AAAA", "standard", "000000"],
["non-ascii-standard", "w6nigqzwn5mC", "standard", "c3a9e282acf09f9982"],
["non-ascii-url", "w6nigqzwn5mC", "url", "c3a9e282acf09f9982"],
];
const errorCases = [
["plus-in-url", "+/8", "url"],
["minus-in-standard", "-_8=", "standard"],
["bang", "Zm9v!", "standard"],
["non-ascii-char", "Zm9vé===", "standard"],
["space", "Zm9v YmFy", "standard"],
["line-feed", "Zm9v\nYmFy", "standard"],
["trailing-crlf", "Zm9vYmFy\r\n", "standard"],
["line-feed-url", "Zm9v\nYmFy", "url"],
["missing-padding", "Zm8", "standard"],
["missing-one-pad", "Zg=", "standard"],
["excess-padding", "Zm9v=", "standard"],
["padding-in-middle", "Zm=9", "standard"],
["three-pads", "Z===", "standard"],
["only-padding", "====", "standard"],
["padding-then-data", "Zg==Zm8=", "standard"],
["padding-in-url", "Zm8=", "url"],
["length-1-mod-4-standard", "Zm9vY", "standard"],
["length-1-mod-4-url", "Zm9vY", "url"],
["one-char-url", "Z", "url"],
["pad-bits-one-byte", "QR==", "standard"],
["pad-bits-two-bytes", "Zm9=", "standard"],
["pad-bits-url", "Zm9", "url"],
];
const fromHex = (hex) => new Uint8Array(Buffer.from(hex, "hex"));
const toHex = (data) => Buffer.from(data).toString("hex");
for (const [name, data, alphabet, want] of encodeCases) {
test(`encode ${name}`, () => {
assert.equal(encode(fromHex(data), alphabet), want);
});
test(`round trip ${name}`, () => {
assert.equal(toHex(decode(encode(fromHex(data), alphabet), alphabet)), data);
});
}
for (const [name, text, alphabet, want] of decodeCases) {
test(`decode ${name}`, () => {
assert.equal(toHex(decode(text, alphabet)), want);
});
}
for (const [name, text, alphabet] of errorCases) {
test(`invalid ${name}`, () => {
assert.throws(() => decode(text, alphabet), SyntaxError);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/base64-encode-and-decode/.
import { Buffer } from "node:buffer";
export type Alphabet = "standard" | "url";
// The Buffer encoding names: "base64" pads with "=", and "base64url"
// adds no padding.
function bufferEncoding(alphabet: Alphabet): BufferEncoding {
if (alphabet === "standard") return "base64";
if (alphabet === "url") return "base64url";
throw new RangeError(`unknown alphabet: ${alphabet}`);
}
/** Encodes the bytes of a Uint8Array as Base64 text. */
export function encode(data: Uint8Array, alphabet: Alphabet = "standard"): string {
const buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
return buf.toString(bufferEncoding(alphabet));
}
/** Decodes Base64 text strictly, and throws a SyntaxError on bad input. */
export function decode(text: string, alphabet: Alphabet = "standard"): Uint8Array {
const encoding = bufferEncoding(alphabet);
// Buffer.from skips characters outside the alphabet, accepts both
// alphabets and does not need the padding. Only the canonical text
// encodes back to itself, so this check rejects everything else.
const data = Buffer.from(text, encoding);
if (data.toString(encoding) !== text) {
throw new SyntaxError(`invalid base64 text: ${JSON.stringify(text)}`);
}
return new Uint8Array(data);
}
b64.test.ts 104 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/base64-encode-and-decode/.
import assert from "node:assert/strict";
import { Buffer } from "node:buffer";
import { test } from "node:test";
import { decode, encode, type Alphabet } from "./b64.ts";
// The bytes are written in hexadecimal.
const encodeCases: [string, string, Alphabet, string][] = [
["rfc-f", "66", "standard", "Zg=="],
["rfc-fo", "666f", "standard", "Zm8="],
["rfc-foo", "666f6f", "standard", "Zm9v"],
["rfc-foob", "666f6f62", "standard", "Zm9vYg=="],
["rfc-fooba", "666f6f6261", "standard", "Zm9vYmE="],
["rfc-foobar", "666f6f626172", "standard", "Zm9vYmFy"],
["hello-standard", "48656c6c6f2c20776f726c6421", "standard", "SGVsbG8sIHdvcmxkIQ=="],
["hello-url", "48656c6c6f2c20776f726c6421", "url", "SGVsbG8sIHdvcmxkIQ"],
["empty-standard", "", "standard", ""],
["empty-url", "", "url", ""],
["two-pad-chars", "00", "standard", "AA=="],
["one-pad-char", "0000", "standard", "AAA="],
["zero-bytes", "000000", "standard", "AAAA"],
["plus-and-slash", "fbff", "standard", "+/8="],
["minus-and-underscore", "fbff", "url", "-_8"],
["all-62-standard", "fbefbe", "standard", "++++"],
["all-62-url", "fbefbe", "url", "----"],
["all-63-standard", "ffffff", "standard", "////"],
["all-63-url", "ffffff", "url", "____"],
["url-one-byte", "66", "url", "Zg"],
["url-two-bytes", "666f", "url", "Zm8"],
["non-ascii-standard", "c3a9e282acf09f9982", "standard", "w6nigqzwn5mC"],
["non-ascii-url", "c3a9e282acf09f9982", "url", "w6nigqzwn5mC"],
];
const decodeCases: [string, string, Alphabet, string][] = [
["rfc-empty", "", "standard", ""],
["rfc-f", "Zg==", "standard", "66"],
["rfc-fo", "Zm8=", "standard", "666f"],
["rfc-foo", "Zm9v", "standard", "666f6f"],
["rfc-foob", "Zm9vYg==", "standard", "666f6f62"],
["rfc-fooba", "Zm9vYmE=", "standard", "666f6f6261"],
["rfc-foobar", "Zm9vYmFy", "standard", "666f6f626172"],
["empty-url", "", "url", ""],
["url-foob", "Zm9vYg", "url", "666f6f62"],
["url-fooba", "Zm9vYmE", "url", "666f6f6261"],
["url-foobar", "Zm9vYmFy", "url", "666f6f626172"],
["plus-and-slash", "+/8=", "standard", "fbff"],
["minus-and-underscore", "-_8", "url", "fbff"],
["all-63-url", "____", "url", "ffffff"],
["zero-bytes", "AAAA", "standard", "000000"],
["non-ascii-standard", "w6nigqzwn5mC", "standard", "c3a9e282acf09f9982"],
["non-ascii-url", "w6nigqzwn5mC", "url", "c3a9e282acf09f9982"],
];
const errorCases: [string, string, Alphabet][] = [
["plus-in-url", "+/8", "url"],
["minus-in-standard", "-_8=", "standard"],
["bang", "Zm9v!", "standard"],
["non-ascii-char", "Zm9vé===", "standard"],
["space", "Zm9v YmFy", "standard"],
["line-feed", "Zm9v\nYmFy", "standard"],
["trailing-crlf", "Zm9vYmFy\r\n", "standard"],
["line-feed-url", "Zm9v\nYmFy", "url"],
["missing-padding", "Zm8", "standard"],
["missing-one-pad", "Zg=", "standard"],
["excess-padding", "Zm9v=", "standard"],
["padding-in-middle", "Zm=9", "standard"],
["three-pads", "Z===", "standard"],
["only-padding", "====", "standard"],
["padding-then-data", "Zg==Zm8=", "standard"],
["padding-in-url", "Zm8=", "url"],
["length-1-mod-4-standard", "Zm9vY", "standard"],
["length-1-mod-4-url", "Zm9vY", "url"],
["one-char-url", "Z", "url"],
["pad-bits-one-byte", "QR==", "standard"],
["pad-bits-two-bytes", "Zm9=", "standard"],
["pad-bits-url", "Zm9", "url"],
];
const fromHex = (hex: string) => new Uint8Array(Buffer.from(hex, "hex"));
const toHex = (data: Uint8Array) => Buffer.from(data).toString("hex");
for (const [name, data, alphabet, want] of encodeCases) {
test(`encode ${name}`, () => {
assert.equal(encode(fromHex(data), alphabet), want);
});
test(`round trip ${name}`, () => {
assert.equal(toHex(decode(encode(fromHex(data), alphabet), alphabet)), data);
});
}
for (const [name, text, alphabet, want] of decodeCases) {
test(`decode ${name}`, () => {
assert.equal(toHex(decode(text, alphabet)), want);
});
}
for (const [name, text, alphabet] of errorCases) {
test(`invalid ${name}`, () => {
assert.throws(() => decode(text, alphabet), SyntaxError);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/base64-encode-and-decode/.
// Package b64 encodes bytes as Base64 text and decodes the text strictly.
package b64
import (
"encoding/base64"
"errors"
"fmt"
"strings"
)
// Alphabet selects one of the two alphabets of RFC 4648.
type Alphabet int
const (
Standard Alphabet = iota // section 4, padded with "="
URL // section 5, with no padding
)
// ErrInvalid is the error for text that is not valid Base64.
var ErrInvalid = errors.New("invalid base64 text")
func (a Alphabet) encoding() *base64.Encoding {
if a == URL {
return base64.RawURLEncoding
}
return base64.StdEncoding
}
// Encode returns the Base64 text of data.
func Encode(data []byte, a Alphabet) string {
return a.encoding().EncodeToString(data)
}
// Decode returns the bytes of text, or an error that wraps ErrInvalid.
func Decode(text string, a Alphabet) ([]byte, error) {
// Strict rejects non-zero pad bits, but the decoder still skips
// "\r" and "\n", so check for them first.
if strings.ContainsAny(text, "\r\n") {
return nil, fmt.Errorf("%w: line break in %q", ErrInvalid, text)
}
data, err := a.encoding().Strict().DecodeString(text)
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrInvalid, err)
}
return data, nil
}
b64_test.go 120 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/base64-encode-and-decode/.
package b64
import (
"encoding/hex"
"errors"
"testing"
)
var alphabets = map[string]Alphabet{"standard": Standard, "url": URL}
// The bytes are written in hexadecimal.
var encodeCases = []struct{ name, data, alphabet, want string }{
{"rfc-f", "66", "standard", "Zg=="},
{"rfc-fo", "666f", "standard", "Zm8="},
{"rfc-foo", "666f6f", "standard", "Zm9v"},
{"rfc-foob", "666f6f62", "standard", "Zm9vYg=="},
{"rfc-fooba", "666f6f6261", "standard", "Zm9vYmE="},
{"rfc-foobar", "666f6f626172", "standard", "Zm9vYmFy"},
{"hello-standard", "48656c6c6f2c20776f726c6421", "standard", "SGVsbG8sIHdvcmxkIQ=="},
{"hello-url", "48656c6c6f2c20776f726c6421", "url", "SGVsbG8sIHdvcmxkIQ"},
{"empty-standard", "", "standard", ""},
{"empty-url", "", "url", ""},
{"two-pad-chars", "00", "standard", "AA=="},
{"one-pad-char", "0000", "standard", "AAA="},
{"zero-bytes", "000000", "standard", "AAAA"},
{"plus-and-slash", "fbff", "standard", "+/8="},
{"minus-and-underscore", "fbff", "url", "-_8"},
{"all-62-standard", "fbefbe", "standard", "++++"},
{"all-62-url", "fbefbe", "url", "----"},
{"all-63-standard", "ffffff", "standard", "////"},
{"all-63-url", "ffffff", "url", "____"},
{"url-one-byte", "66", "url", "Zg"},
{"url-two-bytes", "666f", "url", "Zm8"},
{"non-ascii-standard", "c3a9e282acf09f9982", "standard", "w6nigqzwn5mC"},
{"non-ascii-url", "c3a9e282acf09f9982", "url", "w6nigqzwn5mC"},
}
func TestEncode(t *testing.T) {
for _, c := range encodeCases {
data, _ := hex.DecodeString(c.data)
if got := Encode(data, alphabets[c.alphabet]); got != c.want {
t.Errorf("%s: got %q, want %q", c.name, got, c.want)
}
}
}
func TestRoundTrip(t *testing.T) {
for _, c := range encodeCases {
data, _ := hex.DecodeString(c.data)
a := alphabets[c.alphabet]
got, err := Decode(Encode(data, a), a)
if err != nil || hex.EncodeToString(got) != c.data {
t.Errorf("%s: got %x, %v", c.name, got, err)
}
}
}
func TestDecode(t *testing.T) {
cases := []struct{ name, text, alphabet, want string }{
{"rfc-empty", "", "standard", ""},
{"rfc-f", "Zg==", "standard", "66"},
{"rfc-fo", "Zm8=", "standard", "666f"},
{"rfc-foo", "Zm9v", "standard", "666f6f"},
{"rfc-foob", "Zm9vYg==", "standard", "666f6f62"},
{"rfc-fooba", "Zm9vYmE=", "standard", "666f6f6261"},
{"rfc-foobar", "Zm9vYmFy", "standard", "666f6f626172"},
{"empty-url", "", "url", ""},
{"url-foob", "Zm9vYg", "url", "666f6f62"},
{"url-fooba", "Zm9vYmE", "url", "666f6f6261"},
{"url-foobar", "Zm9vYmFy", "url", "666f6f626172"},
{"plus-and-slash", "+/8=", "standard", "fbff"},
{"minus-and-underscore", "-_8", "url", "fbff"},
{"all-63-url", "____", "url", "ffffff"},
{"zero-bytes", "AAAA", "standard", "000000"},
{"non-ascii-standard", "w6nigqzwn5mC", "standard", "c3a9e282acf09f9982"},
{"non-ascii-url", "w6nigqzwn5mC", "url", "c3a9e282acf09f9982"},
}
for _, c := range cases {
got, err := Decode(c.text, alphabets[c.alphabet])
if err != nil || hex.EncodeToString(got) != c.want {
t.Errorf("%s: got %x, %v, want %s", c.name, got, err, c.want)
}
}
}
func TestInvalid(t *testing.T) {
cases := []struct{ name, text, alphabet string }{
{"plus-in-url", "+/8", "url"},
{"minus-in-standard", "-_8=", "standard"},
{"bang", "Zm9v!", "standard"},
{"non-ascii-char", "Zm9vé===", "standard"},
{"space", "Zm9v YmFy", "standard"},
{"line-feed", "Zm9v\nYmFy", "standard"},
{"trailing-crlf", "Zm9vYmFy\r\n", "standard"},
{"line-feed-url", "Zm9v\nYmFy", "url"},
{"missing-padding", "Zm8", "standard"},
{"missing-one-pad", "Zg=", "standard"},
{"excess-padding", "Zm9v=", "standard"},
{"padding-in-middle", "Zm=9", "standard"},
{"three-pads", "Z===", "standard"},
{"only-padding", "====", "standard"},
{"padding-then-data", "Zg==Zm8=", "standard"},
{"padding-in-url", "Zm8=", "url"},
{"length-1-mod-4-standard", "Zm9vY", "standard"},
{"length-1-mod-4-url", "Zm9vY", "url"},
{"one-char-url", "Z", "url"},
{"pad-bits-one-byte", "QR==", "standard"},
{"pad-bits-two-bytes", "Zm9=", "standard"},
{"pad-bits-url", "Zm9", "url"},
}
for _, c := range cases {
got, err := Decode(c.text, alphabets[c.alphabet])
if !errors.Is(err, ErrInvalid) || got != nil {
t.Errorf("%s: got %x, %v, want ErrInvalid", c.name, got, err)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/base64-encode-and-decode/.
//! Base64 with the two alphabets of RFC 4648 and a strict decoder. The
//! standard library has no Base64, so this file implements it.
use std::fmt;
/// `Standard` is RFC 4648 section 4, padded with `=`. `Url` is section 5,
/// with no padding.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Alphabet {
Standard,
Url,
}
/// The error for text that is not valid Base64.
#[derive(Debug, PartialEq, Eq)]
pub struct InvalidBase64;
impl fmt::Display for InvalidBase64 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("invalid base64 text")
}
}
impl std::error::Error for InvalidBase64 {}
const STANDARD: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const URL: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
const NONE: u8 = 0xff;
/// Maps each byte to its value in the alphabet, or to `NONE`.
const fn values(chars: &[u8; 64]) -> [u8; 256] {
let mut table = [NONE; 256];
let mut i = 0;
while i < 64 {
table[chars[i] as usize] = i as u8;
i += 1;
}
table
}
const STANDARD_VALUES: [u8; 256] = values(STANDARD);
const URL_VALUES: [u8; 256] = values(URL);
/// Returns the Base64 text of `data`.
pub fn encode(data: &[u8], alphabet: Alphabet) -> String {
let chars = match alphabet {
Alphabet::Standard => STANDARD,
Alphabet::Url => URL,
};
let mut text = String::with_capacity(data.len().div_ceil(3) * 4);
for chunk in data.chunks(3) {
// Put the 1 to 3 bytes in the top 24 bits of n, with zero bits after.
let n = chunk.iter().fold(0u32, |n, &b| (n << 8) | u32::from(b)) << (8 * (3 - chunk.len()));
for i in 0..4 {
if i <= chunk.len() {
text.push(char::from(chars[((n >> (18 - 6 * i)) & 63) as usize]));
} else if alphabet == Alphabet::Standard {
text.push('=');
}
}
}
text
}
/// Returns the bytes of `text`. The text must be exactly what [`encode`]
/// gives for some bytes, so white space, a wrong padding and non-zero pad
/// bits are errors.
pub fn decode(text: &str, alphabet: Alphabet) -> Result<Vec<u8>, InvalidBase64> {
let mut body = text.as_bytes();
let values = match alphabet {
Alphabet::Standard => {
if body.len() % 4 != 0 {
return Err(InvalidBase64);
}
// Remove at most two "=" at the end. Any other "=" is not in the
// alphabet, so the loop below rejects it.
for _ in 0..2 {
if let [rest @ .., b'='] = body {
body = rest;
}
}
&STANDARD_VALUES
}
Alphabet::Url => &URL_VALUES,
};
if body.len() % 4 == 1 {
return Err(InvalidBase64);
}
let mut data = Vec::with_capacity(body.len() / 4 * 3 + 2);
for chunk in body.chunks(4) {
let mut n = 0u32;
for &c in chunk {
let v = values[usize::from(c)];
if v == NONE {
return Err(InvalidBase64);
}
n = (n << 6) | u32::from(v);
}
// 4, 3 or 2 characters hold 3, 2 or 1 bytes and 0, 2 or 4 pad bits.
let bytes = chunk.len() * 6 / 8;
let pad_bits = chunk.len() * 6 - bytes * 8;
if n & ((1 << pad_bits) - 1) != 0 {
return Err(InvalidBase64);
}
n >>= pad_bits;
for i in (0..bytes).rev() {
data.push((n >> (8 * i)) as u8);
}
}
Ok(data)
}
tests/b64_test.rs 150 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/base64-encode-and-decode/.
use algo_base64_encode_and_decode::{Alphabet, InvalidBase64, decode, encode};
fn alphabet(name: &str) -> Alphabet {
if name == "url" {
Alphabet::Url
} else {
Alphabet::Standard
}
}
fn from_hex(hex: &str) -> Vec<u8> {
(0..hex.len())
.step_by(2)
.map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap())
.collect()
}
fn to_hex(data: &[u8]) -> String {
data.iter().map(|b| format!("{b:02x}")).collect()
}
// The bytes are written in hexadecimal.
const ENCODE: &[(&str, &str, &str, &str)] = &[
("rfc-f", "66", "standard", "Zg=="),
("rfc-fo", "666f", "standard", "Zm8="),
("rfc-foo", "666f6f", "standard", "Zm9v"),
("rfc-foob", "666f6f62", "standard", "Zm9vYg=="),
("rfc-fooba", "666f6f6261", "standard", "Zm9vYmE="),
("rfc-foobar", "666f6f626172", "standard", "Zm9vYmFy"),
(
"hello-standard",
"48656c6c6f2c20776f726c6421",
"standard",
"SGVsbG8sIHdvcmxkIQ==",
),
(
"hello-url",
"48656c6c6f2c20776f726c6421",
"url",
"SGVsbG8sIHdvcmxkIQ",
),
("empty-standard", "", "standard", ""),
("empty-url", "", "url", ""),
("two-pad-chars", "00", "standard", "AA=="),
("one-pad-char", "0000", "standard", "AAA="),
("zero-bytes", "000000", "standard", "AAAA"),
("plus-and-slash", "fbff", "standard", "+/8="),
("minus-and-underscore", "fbff", "url", "-_8"),
("all-62-standard", "fbefbe", "standard", "++++"),
("all-62-url", "fbefbe", "url", "----"),
("all-63-standard", "ffffff", "standard", "////"),
("all-63-url", "ffffff", "url", "____"),
("url-one-byte", "66", "url", "Zg"),
("url-two-bytes", "666f", "url", "Zm8"),
(
"non-ascii-standard",
"c3a9e282acf09f9982",
"standard",
"w6nigqzwn5mC",
),
("non-ascii-url", "c3a9e282acf09f9982", "url", "w6nigqzwn5mC"),
];
#[test]
fn encode_cases() {
for &(name, data, a, want) in ENCODE {
assert_eq!(encode(&from_hex(data), alphabet(a)), want, "{name}");
}
}
#[test]
fn round_trip() {
for &(name, data, a, _) in ENCODE {
let text = encode(&from_hex(data), alphabet(a));
assert_eq!(
decode(&text, alphabet(a)).map(|d| to_hex(&d)),
Ok(data.to_string()),
"{name}"
);
}
}
#[test]
fn decode_cases() {
let cases: &[(&str, &str, &str, &str)] = &[
("rfc-empty", "", "standard", ""),
("rfc-f", "Zg==", "standard", "66"),
("rfc-fo", "Zm8=", "standard", "666f"),
("rfc-foo", "Zm9v", "standard", "666f6f"),
("rfc-foob", "Zm9vYg==", "standard", "666f6f62"),
("rfc-fooba", "Zm9vYmE=", "standard", "666f6f6261"),
("rfc-foobar", "Zm9vYmFy", "standard", "666f6f626172"),
("empty-url", "", "url", ""),
("url-foob", "Zm9vYg", "url", "666f6f62"),
("url-fooba", "Zm9vYmE", "url", "666f6f6261"),
("url-foobar", "Zm9vYmFy", "url", "666f6f626172"),
("plus-and-slash", "+/8=", "standard", "fbff"),
("minus-and-underscore", "-_8", "url", "fbff"),
("all-63-url", "____", "url", "ffffff"),
("zero-bytes", "AAAA", "standard", "000000"),
(
"non-ascii-standard",
"w6nigqzwn5mC",
"standard",
"c3a9e282acf09f9982",
),
("non-ascii-url", "w6nigqzwn5mC", "url", "c3a9e282acf09f9982"),
];
for &(name, text, a, want) in cases {
assert_eq!(
decode(text, alphabet(a)).map(|d| to_hex(&d)),
Ok(want.to_string()),
"{name}"
);
}
}
#[test]
fn invalid() {
let cases: &[(&str, &str, &str)] = &[
("plus-in-url", "+/8", "url"),
("minus-in-standard", "-_8=", "standard"),
("bang", "Zm9v!", "standard"),
("non-ascii-char", "Zm9vé===", "standard"),
("space", "Zm9v YmFy", "standard"),
("line-feed", "Zm9v\nYmFy", "standard"),
("trailing-crlf", "Zm9vYmFy\r\n", "standard"),
("line-feed-url", "Zm9v\nYmFy", "url"),
("missing-padding", "Zm8", "standard"),
("missing-one-pad", "Zg=", "standard"),
("excess-padding", "Zm9v=", "standard"),
("padding-in-middle", "Zm=9", "standard"),
("three-pads", "Z===", "standard"),
("only-padding", "====", "standard"),
("padding-then-data", "Zg==Zm8=", "standard"),
("padding-in-url", "Zm8=", "url"),
("length-1-mod-4-standard", "Zm9vY", "standard"),
("length-1-mod-4-url", "Zm9vY", "url"),
("one-char-url", "Z", "url"),
("pad-bits-one-byte", "QR==", "standard"),
("pad-bits-two-bytes", "Zm9=", "standard"),
("pad-bits-url", "Zm9", "url"),
];
for &(name, text, a) in cases {
assert_eq!(decode(text, alphabet(a)), Err(InvalidBase64), "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/base64-encode-and-decode/.
# Base64 with the two alphabets of RFC 4648: "standard" pads with "=",
# and "url" uses "-" and "_" for "+" and "/" and has no padding.
_B64_ALNUM='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
# b64_encode ALPHABET: reads bytes on stdin and prints their Base64 text.
b64_encode() {
local text
case $1 in
standard | url) ;;
*)
echo "b64_encode: unknown alphabet: $1" >&2
return 2
;;
esac
# GNU base64 breaks the output into lines of 76 characters, and BSD
# base64 does not. Remove every newline, so both give one line.
text=$(base64 | tr -d '\n') || return
if [[ $1 == url ]]; then
text=${text//+/-}
text=${text//\//_}
text=${text%%=*}
fi
printf '%s\n' "$text"
}
# b64_decode TEXT ALPHABET: writes the bytes of TEXT to stdout. TEXT must be
# exactly what b64_encode prints for some bytes, or the status is 1.
b64_decode() {
local text=$1 c re
# The pattern checks the alphabet, the length and the padding. The last
# data character must have zero pad bits: its value is a multiple of 16
# (A, Q, g, w) before "==", and a multiple of 4 before "=".
case $2 in
standard)
c="[${_B64_ALNUM}+/]"
re="^($c{4})*($c[AQgw]==|$c{2}[AEIMQUYcgkosw048]=)?\$"
;;
url)
c="[${_B64_ALNUM}_-]"
re="^($c{4})*($c[AQgw]|$c{2}[AEIMQUYcgkosw048])?\$"
;;
*)
echo "b64_decode: unknown alphabet: $2" >&2
return 2
;;
esac
if ! [[ $text =~ $re ]]; then
echo "b64_decode: invalid base64 text" >&2
return 1
fi
text=${text//-/+}
text=${text//_//}
while ((${#text} % 4)); do
text+='='
done
printf '%s' "$text" | base64 -d
}
test_b64.bats 112 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/base64-encode-and-decode/.
setup() {
source "$BATS_TEST_DIRNAME/b64.sh"
set -o pipefail
}
# unhex HEX: writes the bytes of HEX to stdout.
unhex() {
local hex=$1 escapes=''
while [[ -n $hex ]]; do
escapes+="\\x${hex:0:2}"
hex=${hex:2}
done
printf '%b' "$escapes"
}
# tohex: prints the bytes on stdin in hexadecimal.
tohex() {
od -An -tx1 -v | tr -d ' \n'
}
# check_encode HEX ALPHABET WANT: checks the text and the round trip.
check_encode() {
local text back
text=$(unhex "$1" | b64_encode "$2")
[[ $text == "$3" ]] || { echo "got '$text', want '$3'" >&2; return 1; }
back=$(b64_decode "$text" "$2" | tohex)
[[ $back == "$1" ]] || { echo "round trip gave '$back'" >&2; return 1; }
}
# check_decode TEXT ALPHABET WANT: WANT is the bytes in hexadecimal.
check_decode() {
local got
got=$(b64_decode "$1" "$2" | tohex)
[[ $got == "$3" ]] || { echo "got '$got', want '$3'" >&2; return 1; }
}
# check_invalid TEXT ALPHABET: decode must fail with status 1 and write no bytes.
check_invalid() {
local got status=0
got=$(b64_decode "$1" "$2" 2>/dev/null | tohex) || status=$?
[[ $status -eq 1 && -z $got ]] || { echo "status $status, bytes '$got'" >&2; return 1; }
}
# The bytes are written in hexadecimal.
@test "encode rfc-f" { check_encode '66' standard 'Zg=='; }
@test "encode rfc-fo" { check_encode '666f' standard 'Zm8='; }
@test "encode rfc-foo" { check_encode '666f6f' standard 'Zm9v'; }
@test "encode rfc-foob" { check_encode '666f6f62' standard 'Zm9vYg=='; }
@test "encode rfc-fooba" { check_encode '666f6f6261' standard 'Zm9vYmE='; }
@test "encode rfc-foobar" { check_encode '666f6f626172' standard 'Zm9vYmFy'; }
@test "encode hello-standard" { check_encode '48656c6c6f2c20776f726c6421' standard 'SGVsbG8sIHdvcmxkIQ=='; }
@test "encode hello-url" { check_encode '48656c6c6f2c20776f726c6421' url 'SGVsbG8sIHdvcmxkIQ'; }
@test "encode empty-standard" { check_encode '' standard ''; }
@test "encode empty-url" { check_encode '' url ''; }
@test "encode two-pad-chars" { check_encode '00' standard 'AA=='; }
@test "encode one-pad-char" { check_encode '0000' standard 'AAA='; }
@test "encode zero-bytes" { check_encode '000000' standard 'AAAA'; }
@test "encode plus-and-slash" { check_encode 'fbff' standard '+/8='; }
@test "encode minus-and-underscore" { check_encode 'fbff' url '-_8'; }
@test "encode all-62-standard" { check_encode 'fbefbe' standard '++++'; }
@test "encode all-62-url" { check_encode 'fbefbe' url '----'; }
@test "encode all-63-standard" { check_encode 'ffffff' standard '////'; }
@test "encode all-63-url" { check_encode 'ffffff' url '____'; }
@test "encode url-one-byte" { check_encode '66' url 'Zg'; }
@test "encode url-two-bytes" { check_encode '666f' url 'Zm8'; }
@test "encode non-ascii-standard" { check_encode 'c3a9e282acf09f9982' standard 'w6nigqzwn5mC'; }
@test "encode non-ascii-url" { check_encode 'c3a9e282acf09f9982' url 'w6nigqzwn5mC'; }
@test "decode rfc-empty" { check_decode '' standard ''; }
@test "decode rfc-f" { check_decode 'Zg==' standard '66'; }
@test "decode rfc-fo" { check_decode 'Zm8=' standard '666f'; }
@test "decode rfc-foo" { check_decode 'Zm9v' standard '666f6f'; }
@test "decode rfc-foob" { check_decode 'Zm9vYg==' standard '666f6f62'; }
@test "decode rfc-fooba" { check_decode 'Zm9vYmE=' standard '666f6f6261'; }
@test "decode rfc-foobar" { check_decode 'Zm9vYmFy' standard '666f6f626172'; }
@test "decode empty-url" { check_decode '' url ''; }
@test "decode url-foob" { check_decode 'Zm9vYg' url '666f6f62'; }
@test "decode url-fooba" { check_decode 'Zm9vYmE' url '666f6f6261'; }
@test "decode url-foobar" { check_decode 'Zm9vYmFy' url '666f6f626172'; }
@test "decode plus-and-slash" { check_decode '+/8=' standard 'fbff'; }
@test "decode minus-and-underscore" { check_decode '-_8' url 'fbff'; }
@test "decode all-63-url" { check_decode '____' url 'ffffff'; }
@test "decode zero-bytes" { check_decode 'AAAA' standard '000000'; }
@test "decode non-ascii-standard" { check_decode 'w6nigqzwn5mC' standard 'c3a9e282acf09f9982'; }
@test "decode non-ascii-url" { check_decode 'w6nigqzwn5mC' url 'c3a9e282acf09f9982'; }
@test "invalid plus-in-url" { check_invalid '+/8' url; }
@test "invalid minus-in-standard" { check_invalid '-_8=' standard; }
@test "invalid bang" { check_invalid 'Zm9v!' standard; }
@test "invalid non-ascii-char" { check_invalid 'Zm9vé===' standard; }
@test "invalid space" { check_invalid 'Zm9v YmFy' standard; }
@test "invalid line-feed" { check_invalid $'Zm9v\nYmFy' standard; }
@test "invalid trailing-crlf" { check_invalid $'Zm9vYmFy\r\n' standard; }
@test "invalid line-feed-url" { check_invalid $'Zm9v\nYmFy' url; }
@test "invalid missing-padding" { check_invalid 'Zm8' standard; }
@test "invalid missing-one-pad" { check_invalid 'Zg=' standard; }
@test "invalid excess-padding" { check_invalid 'Zm9v=' standard; }
@test "invalid padding-in-middle" { check_invalid 'Zm=9' standard; }
@test "invalid three-pads" { check_invalid 'Z===' standard; }
@test "invalid only-padding" { check_invalid '====' standard; }
@test "invalid padding-then-data" { check_invalid 'Zg==Zm8=' standard; }
@test "invalid padding-in-url" { check_invalid 'Zm8=' url; }
@test "invalid length-1-mod-4-standard" { check_invalid 'Zm9vY' standard; }
@test "invalid length-1-mod-4-url" { check_invalid 'Zm9vY' url; }
@test "invalid one-char-url" { check_invalid 'Z' url; }
@test "invalid pad-bits-one-byte" { check_invalid 'QR==' standard; }
@test "invalid pad-bits-two-bytes" { check_invalid 'Zm9=' standard; }
@test "invalid pad-bits-url" { check_invalid 'Zm9' url; }
References
- RFC 4648, The Base16, Base32, and Base64 Data Encodings, 3.1 Line Feeds in Encoded Data, 3.2 Padding of Encoded Data, 3.3 Interpretation of Non-Alphabet Characters in Encoded Data, 3.5 Canonical Encoding, 4 Base 64 Encoding, 5 Base 64 Encoding with URL and Filename Safe Alphabet, 10 Test Vectors, 12 Security Considerations
- RFC 7515, JSON Web Signature (JWS), 2 Terminology, Base64url Encoding
- RFC 2045, Multipurpose Internet Mail Extensions (MIME) Part One, 6.8 Base64 Content-Transfer-Encoding
- The Python Standard Library, base64, b64encode, b64decode, urlsafe_b64encode
- Node.js documentation, Buffer, Buffers and character encodings, 'base64' and 'base64url'
- MDN Web Docs, Window.btoa(), Exceptions, Unicode strings
- Java SE 25 API, java.util.Base64, class description (Basic, URL and Filename safe, MIME)
- Java SE 25 API, java.util.Base64.Encoder, withoutPadding()
- Java SE 25 API, java.util.Base64.Decoder, class description
- .NET API reference, Convert.FromBase64String, Remarks, Exceptions
- .NET API reference, Base64Url, EncodeToString, DecodeFromChars
- .NET API reference, Encoding.Unicode, Definition
- Go standard library, package encoding/base64, StdEncoding, RawURLEncoding, Encoding.Strict, Encoding.Decode
- Linux man-pages, base64(1), Description, -d, -w
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
The native tests pass in 9 of 10 languages in this build.
Tag 5BX5KR Edit this page History Report an error Markdown