Skip to content

Instantly share code, notes, and snippets.

@meqif
Created June 16, 2009 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meqif/130890 to your computer and use it in GitHub Desktop.
Save meqif/130890 to your computer and use it in GitHub Desktop.
Base64 decoder
/*
* Copyright (c) 2009 Ricardo Martins <ricardo@scarybox.net>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <stdlib.h>
#include <string.h>
static const char *base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
char *decode64(const char *orig)
{
int i, j;
size_t length = strlen(orig);
char *in, *out, *head;
union x {
char data[3];
int as_integer;
} alpha;
in = malloc(length - (length%4) + 4 + 1);
memset(in, '=', length - (length%4) + 4);
strcpy(in, orig);
out = calloc(length+1, sizeof(char));
head = out;
for (i = 0; i < length; i++) {
for (j = 0; in[i] != '=' && in[i] != base64[j]; j++);
in[i] = j;
}
for (i = 0; i < length; i += 4) {
alpha.as_integer = in[i] << 18;
alpha.as_integer |= in[i+1] << 12;
alpha.as_integer |= in[i+2] << 6;
alpha.as_integer |= in[i+3];
*(head++) = alpha.data[2];
*(head++) = alpha.data[1];
*(head++) = alpha.data[0];
}
*head = 0;
free(in);
return out;
}
int main(void)
{
char *text =
"TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aG"
"lzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qg"
"b2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY2"
"9udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNl"
"ZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=";
char *out = decode64(text);
printf("%s\n", out);
free(out);
return 0;
}
// vim: et ts=4 sw=4 sts=4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment