Created
July 28, 2012 14:26
-
-
Save deltheil/3193603 to your computer and use it in GitHub Desktop.
base64url without padding decoding (with TC)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* How to use it | |
* -- | |
* brew install tokyo-cabinet | |
* clang -o b64 b64.c -Wall -Werror -I/usr/local/include -L/usr/local/lib -ltokyocabinet | |
* ./b64 | |
* ./b64 Zm9v | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <assert.h> | |
#include <string.h> | |
#include <tcutil.h> | |
struct { | |
const char *in; | |
const char *out; | |
} b64_tests[] = { | |
/* empty string test */ | |
{"", ""}, | |
/* '==' padding test */ | |
{"Zg", "f"}, | |
/* '=' padding test */ | |
{"Zm8", "fo"}, | |
/* no padding test */ | |
{"Zm9v", "foo"}, | |
/* misc test */ | |
{"eyJmb28iOiJiYXIifQ", "{\"foo\":\"bar\"}"}, | |
/* '-_' to '+/' character substitution test */ | |
{"NSUyKzMtMT0zICJZZXMvTm8iIDxhJmI-", "5%2+3-1=3 \"Yes/No\" <a&b>"} | |
}; | |
/* base64url (aka URL safe) without padding decoding */ | |
char *b64urldecode(const char *str, int *sp); | |
int main(int argc, char **argv) { | |
int siz; | |
char *buf; | |
if (argc > 2) { | |
fprintf(stderr, "Usage: %s [str]\n", argv[0]); | |
exit(1); | |
} | |
if (argc == 2) { | |
printf("IN: %s\n", argv[1]); | |
buf = b64urldecode(argv[1], &siz); | |
printf("OUT: %s\n", buf); | |
free(buf); | |
} | |
else { | |
int ntests = (sizeof(b64_tests)/sizeof(b64_tests[0])); | |
for (int i = 0; i < ntests; i++) { | |
buf = b64urldecode(b64_tests[i].in, &siz); | |
if (siz == strlen(b64_tests[i].out) && !strcmp(buf, b64_tests[i].out)) | |
fprintf(stdout, "test #%d\t[OK]\n", i + 1); | |
else { | |
fprintf(stderr, "test #%d\t[KO]", i + 1); | |
fprintf(stderr, " got `%s', expected `%s'\n", buf, b64_tests[i].out); | |
} | |
free(buf); | |
} | |
} | |
return 0; | |
} | |
char *b64urldecode(const char *str, int *sp) { | |
assert(str && sp); | |
int len = strlen(str); | |
char *buf = malloc(len + 3); | |
memcpy(buf, str, len); | |
while ((len % 4) >= 2) buf[len++] = '='; | |
buf[len] = '\0'; | |
tcstrsubchr(buf, "-_", "+/"); | |
char *obuf = tcbasedecode(buf, sp); | |
free(buf); | |
return obuf; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment