Base64 Kodierung in C

base64 codierung mit glib

#include <stdio.h>
#include <glib.h>

int main(int argc, char **argv)
{
        char *s;

        s=g_base64_encode("Hallo Welt", 10);
        printf("%s\n", s);
}

Base64 Encode

Eine Implementierung von Base58 Kodierung in C ohne irgendwelche Abhängigkeiten. Läuft auch effizient auf Microcontrollern, wenn man mit fixen Puffern anstatt malloc() arbeitet.

#include <stdio.h>
#include <stdint.h>
#include <malloc.h>
#include <string.h>

static const char base64_table[65] =
	"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

char* base64_encode(const uint8_t* src, size_t len)
{
	size_t output_len = 4 * ((len + 2) / 3);	/* each 3 bytes input results in 4 bytes of output */
	if (output_len < len) {
		return NULL; 			/* integer overflow happened */
	}
	char* buf = malloc(output_len + 1);
	if (buf == NULL) {
		return NULL;
	}
	const uint8_t* end = src + len;
	char* wptr = buf;
	for ( ; end - src >= 3; src += 3) {
		*wptr++ = base64_table[src[0] >> 2];
		*wptr++ = base64_table[((src[0] & 0x03) << 4) | (src[1] >> 4)];
		*wptr++ = base64_table[((src[1] & 0x0f) << 2) | (src[2] >> 6)];
		*wptr++ = base64_table[src[2] & 0x3f];
	}
	if (end != src) {
		*wptr++ = base64_table[src[0] >> 2];
		if (end - src == 1) {
			*wptr++ = base64_table[(src[0] & 0x03) << 4];
			*wptr++ = '=';
		} else {
			*wptr++ = base64_table[((src[0] & 0x03) << 4) | (src[1] >> 4)];
			*wptr++ = base64_table[(src[1] & 0x0f) << 2];
		}
		*wptr++ = '=';
	}
	*wptr = 0;
	return buf;
}

Base64 Encode mit der OpenSSL Library

Wer der Meinung ist, lieber eine fertige Library verwenden zu müssen als handgeschnitzten Code, kann das hier verwenden:

#include <stdint.h>
#include <malloc.h>
#include <string.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/buffer.h>

char *base64enc(const unsigned char *input, size_t length)
{
	BIO *bmem, *b64;
	BUF_MEM *bptr;

	b64 = BIO_new(BIO_f_base64());
	bmem = BIO_new(BIO_s_mem());
	b64 = BIO_push(b64, bmem);

	BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); // dont write newline
	BIO_write(b64, input, length);
	BIO_flush(b64);
	BIO_get_mem_ptr(b64, &bptr);
	
	char *buf = (char *)malloc(bptr->length+1);
	memcpy(buf, bptr->data, bptr->length);
	buf[bptr->length] = 0;
	BIO_free_all(b64);
	return buf;
}