Base64 Encode Decode in Mathematica

Published on 30 April 2026 (Updated: 30 April 2026)

Welcome to the Base64 Encode Decode in Mathematica page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

ClearAll[base64Main];

NonEmptyStringQ = StringQ[#] && StringTrim[#] =!= "" &;

ValidBase64Q[s_String] :=
  StringLength[s] > 0 &&
  Mod[StringLength[s], 4] == 0 &&
  StringMatchQ[s, RegularExpression["^[A-Za-z0-9+/]*={0,2}$"]];

base64Main["encode", s_String?NonEmptyStringQ] :=
  StringTrim[ExportString[s, "Base64"]];

base64Main["decode", s_String?ValidBase64Q]  :=
  StringTrim[ImportString[s, "Base64"]];

base64Main[___] := "Usage: please provide a mode and a string to encode/decode";

validCases = {
  {"encode", "hello world"},
  {"encode", "They swam along the boat at incredible speeds."},
  {"encode", "1234567890"},
  {"encode", "xyz!#$%&()*+,-./:;<=>?@[\\]^_`{|}~"},
  {"encode", "!  }gggIIT55;qqs!!Gjjb??=~~2$$+;;i::x..4kk,ppnoo"},
  {"decode", "aGVsbG8gd29ybGQ="},
  {"decode", "VGhleSBzd2FtIGFsb25nIHRoZSBib2F0IGF0IGluY3JlZGlibGUgc3BlZWRzLg=="},
  {"decode", "MTIzNDU2Nzg5MA=="},
  {"decode", "eHl6ISMkJSYoKSorLC0uLzo7PD0+P0BbXF1eX2B7fH1+"},
  {"decode", "ISAgfWdnZ0lJVDU1O3FxcyEhR2pqYj8/PX5+MiQkKzs7aTo6eC4uNGtrLHBwbm9v"}
};

invalidCases = {
  {},
  {""},
  {"encode"},
  {"encode", ""},
  {"decode"},
  {"decode", ""},
  {"blue", "Oh look a Pascal triangle"},
  {"decode", "hello+world"},
  {"decode", "hello world="},
  {"decode", "MTIzNDU2Nzg5M==="},
  {"decode", "MTIzNDU2=Nzg5M=="}
};

runTest[{a___}] := Print[base64Main[a]];
Scan[runTest, Join[validCases, invalidCases]];

Base64 Encode Decode in Mathematica was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.