Skip to content

Instantly share code, notes, and snippets.

@toboqus
Last active September 2, 2022 06:09
Show Gist options
  • Save toboqus/5bb75442b7535b68a65906f6663ba3ce to your computer and use it in GitHub Desktop.
Save toboqus/5bb75442b7535b68a65906f6663ba3ce to your computer and use it in GitHub Desktop.
Base64 in C
#include <stdlib.h>
#include "base64.h"
static char values[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
static int indexOf(char * array, char value){
int i;
for(i = 0; *array; ++i, ++array)
if(*array == value)
return i;
return -1;
}
static unsigned long size(char * input){ //will calculate size up to 2^64-1 bytes
long length = 0;
while(*input++)
length++;
return length;
}
static char valid(char value){ //check to see if the char is valid
return (value < 64 && value >= 0) ? 1 : 0;
}
static unsigned char * getMem(unsigned long inputSize, char value){
return malloc(1+ (value == ENCODE) ? ((inputSize * 4)/3): ((inputSize * 3)/4));
}
unsigned char *encode(char *input){
unsigned long len = size(input), i;
unsigned char *res = getMem(len, ENCODE), *p = res, b;
for(i = 0; i < len; i += 3){
b = (input[i] & 0xFC) >> 2;
*p++ = values[b];
b = (input[i] & 0x03) << 4;
if(i+1 < len){
b |= ((input[i+1] & 0xf0) >> 4);
*p++ = values[b];
b = (input[i+1] & 0x0F) << 2;
if(i+2 < len){
b |= (input[i+2] & 0xC0) >> 6;
*p++ = values[b];
b = (input[i+2] & 0x3F);
*p++ = values[b];
}else{
*p++ = values[b];
*p++ = values[64];
*p++ = values[64];
}
}else{
*p++ = values[b];
*p++ = values[64];
}
}
*p = '\0';
return res;
}
unsigned char *decode(char *input){
unsigned long len = size(input), i;
unsigned char *res = getMem(len, DECODE), *p = res, b[4];
for(i = 0; i < len; i += 4){
int a;
for(a = 0; a < 4; a++){
b[a] = indexOf(values,input[i+a]);
}
if(!valid(b[0])){
*p++ = (b[0] << 2);
}else{
*p++ = (b[0] << 2) | ((valid(b[1])) ? (b[1] >> 4) : 0);
if(valid(b[1])){
*p++ = (b[1] << 4) | ((valid(b[2])) ? (b[2] >> 2) : 0);
if(valid(b[2])){
*p++ = (b[2] << 6) | ((valid(b[3])) ? b[3] : 0);
}
}
}
}
*p = '\0';
return res;
}
#ifndef BASE64_H_
#define BASE64_H_
#define ENCODE 0
#define DECODE 1
unsigned char * encode(char * input);
unsigned char * decode(char * input);
#endif /* BASE64_H_ */
#include <stdio.h>
#include "base64.h"
int main(void){
char * res = "This is an encoded message into base64 and should display properly without errors!!";
printf("%s\n\n", res);
char * encoded = encode(res);
printf("%s\n\n", encoded);
char * decoded = decode(encoded);
printf("%s\n\n", decoded);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment