Skip to content

Instantly share code, notes, and snippets.

@odzhan
Last active October 18, 2020 03:53
Show Gist options
  • Save odzhan/09cd906789b0b999cde44525e56613f8 to your computer and use it in GitHub Desktop.
Save odzhan/09cd906789b0b999cde44525e56613f8 to your computer and use it in GitHub Desktop.
Compact implementation of Base64 encoding in C
/**
BSD 3-Clause License
Copyright (c) 2019 Odzhan. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <inttypes.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifndef _MSC_VER
#include <unistd.h>
#endif
#define ROTL32(v,n)(((v)<<(n))|((v)>>(32-(n))))
#ifdef _MSC_VER
#define rev32(x) _byteswap_ulong(x)
#else
#define rev32(x) __builtin_bswap32(x)
#endif
// calculate length of buffer required for base64 encoding
#define B64_LEN(N) (((4 * (N / 3)) + 4) & -4)
static const char b64_tbl[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// openssl base64 -A -e -in <binary> -out binary.base64
// Compact implementation of base64 encoding. Probably slow as hell.
// The main encoding loop is inspired by Qkumba AKA Peter Ferrie, except this
// uses a lookup table.
//
static int b64_encode(
const void *src, uint64_t inlen,
void *dst, uint64_t *outlen, int last)
{
uint64_t len;
uint32_t x;
int i = 0;
uint8_t *in = (uint8_t*)src, *out = (uint8_t*)dst;
// check arguments
if(outlen == NULL) return 0;
// calculate length of buffer required for encoded string
len = B64_LEN(inlen);
// return the length?
if(out == NULL) {
*outlen = len;
return 1;
}
// can buffer contain string?
if(len > *outlen) return 0;
// main encoding loop
while(inlen != 0) {
// load 3 bytes
for(x=i=0; i<3; i++) {
x |= ((i < inlen) ? *in++ : 0);
x <<= 8;
}
// increase by 1
inlen++;
// encode 3 bytes
for(i=4; inlen && i>0; i--) {
x = ROTL32(x, 6);
*out++ = b64_tbl[x % 64];
--inlen;
}
}
// if required, add padding
if(last) {
while(i!=0) { *out++ = '='; i--; }
// add null terminator
*out = 0;
}
// calculate output length by subtracting 2 pointers
*outlen = (out - (uint8_t*)dst);
return 1;
}
int main(int argc, char *argv[]) {
char *input;
uint64_t inlen, outlen;
void *output;
FILE *in, *out;
uint8_t buf[255], str[B64_LEN(sizeof(buf))];
if(argc < 2) {
printf("usage: base64 <string> | <infile> <outfile>\n");
return 0;
}
if(argc == 2) {
input = argv[1];
inlen = strlen(argv[1]);
// calculate length
if(b64_encode(NULL, inlen, NULL, &outlen, 1)) {
// allocate memory
output = malloc(outlen);
if(output != NULL) {
// encode input
if(b64_encode(input, inlen, output, &outlen, 1)) {
printf("%s\n", (char*)output);
}
// release memory
free(output);
}
}
} else
if(argc == 3) {
in = fopen(argv[1], "rb");
if(in == NULL) {
printf("unable to open %s\n", argv[1]);
return -1;
}
out = fopen(argv[2], "wb");
if(out != NULL) {
for(;;) {
// read block
inlen = fread(buf, 1, sizeof(buf), in);
// nothing read? break
if(inlen == 0) break;
// encode
outlen = sizeof(str);
if(!b64_encode(buf, inlen, str, &outlen, inlen<sizeof(buf))) {
printf("encoding failed.\n");
break;
}
// save to file
fwrite(str, 1, outlen, out);
}
fclose(out);
} else printf("unable to open %s\n", argv[2]);
fclose(in);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment