Skip to content

Instantly share code, notes, and snippets.

@aji
Created May 28, 2013 03:01
Show Gist options
  • Save aji/5660269 to your computer and use it in GitHub Desktop.
Save aji/5660269 to your computer and use it in GitHub Desktop.
#include <stdint.h>
#include <stdlib.h>
#define BLANK 64
static char *enc =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
static uint8_t dec[256];
static void make_dec(void)
{
char *s;
if (dec[enc[3]] == 3) /* stupid test, but it works.. */
return;
for (s=enc; *s; s++)
dec[*s] = (s - enc) & 0x3f;
}
static size_t encode_triplet(char *dst, uint8_t *src, size_t n)
{
uint8_t s[3];
s[0] = n > 0 ? src[0] : 0;
s[1] = n > 1 ? src[1] : 0;
s[2] = n > 2 ? src[2] : 0;
dst[0] = enc[((s[0] ) >> 2) ];
dst[1] = enc[((s[0] & 0x03) << 4) | ((s[1] & 0xf0) >> 4)];
dst[2] = enc[((s[1] & 0x0f) << 2) | ((s[2] & 0xc0) >> 6)];
dst[3] = enc[((s[2] & 0x3f) ) ];
if (n < 2) dst[2] = enc[BLANK];
if (n < 3) dst[3] = enc[BLANK];
return 4;
}
static size_t decode_triplet(char *s, uint8_t *dst)
{
dst[0] = (dec[s[0]] << 2) | (dec[s[1]] >> 4);
dst[1] = (dec[s[1]] << 4) | (dec[s[2]] >> 2);
dst[2] = (dec[s[2]] << 6) | (dec[s[3]] );
return 1 + (s[2] != enc[BLANK]) + (s[3] != enc[BLANK]);
}
size_t b64_encode(char *dst, uint8_t *src, size_t n)
{
char *d = dst;
uint8_t *s = src;
for (; s < src + n; s += 3)
d += encode_triplet(d, s, src + n - s);
return d - dst;
}
size_t b64_decode(char *src, uint8_t *dst)
{
uint8_t *d = dst;
char *s = src;
make_dec();
for (; s[0] && s[1] && s[2] && s[3]; s += 4)
d += decode_triplet(s, d);
return d - dst;
}
#include <stdint.h>
#include <string.h>
#include <stdio.h>
extern size_t b64_encode(char *dst, uint8_t *src, size_t n);
extern size_t b64_decode(char *src, uint8_t *dst);
char *message =
"Man is distinguished, not only by his reason, but by this singular "
"passion from other animals, which is a lust of the mind, that by a "
"perseverance of delight in the continued and indefatigable generation "
"of knowledge, exceeds the short vehemence of any carnal pleasure.";
char encd[65536];
char decd[65536];
int main(int argc, char *argv[])
{
size_t n;
n = b64_encode(encd, message, strlen(message));
encd[n] = '\0';
puts(encd);
n = b64_decode(encd, decd);
decd[n] = '\0';
puts(decd);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment