C ile Base64 Kodlama

Eğer ki C programlama dili ile bir smtp uygulaması yazmaya çalışıyorsanız, muhtemelen mail ile birlikte bir ek dosya yollama ihtiyacı duyacaksınızdır. Bunu gerçekleştirme noktasında verimizi açtığımız smtp soketine yazarken base64 kodlama sistemi kullanarak bunu gerçekleştirmemiz gerekmektedir.


char  encoded[1024];
static const char base64EncTable[64]="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
//Convert a char array to bits
char *foo(char *dst, unsigned char value)
{
unsigned char bit;
char *start=dst;
for (bit=1<<(CHAR_BIT-1);bit;bit>>=1)
{
*dst++=value & bit? '1':'0';
}
*dst='\0';
return start;

}

//Encode with base64
encodeBin2Base(char *msg)
{
unsigned char u;
int i,dec;
char c;
char temp[10];
char printable[1024];

//initilaze arrays
strcpy(printable,"");
strcpy(temp,"");
strcpy(encoded,"");

for(i=0;i<strlen(msg);i++)
{
u=msg[i];
char b[CHAR_BIT*sizeof(u)+1];

strcat(binCode,foo(b,u));

//printf("%s",foo(b,u));
}

for(i=0;i<strlen(binCode);i++)
{
if((i)%6==0)
{

strcat(temp,"00");
strncat(temp,&binCode[i],6);
dec=bin2dec(temp);
strncat(encoded,&base64EncTable[dec],1);
strcpy(temp,"");
}

}

}

// convert a binary string to a decimal number, returns decimal value

int bin2dec(char *bin)
{

int b, k, m, n;
int len, sum = 0;
len = strlen(bin) - 1;

for(k = 0; k <= len; k++)
{
n = (bin[k] - '0'); // char to numeric value

if ((n > 1) || (n < 0))
{
puts("\n\n ERROR! BINARY has only 1 and 0!\n");
return (0);
}

for(b = 1, m = len; m > k; m--)
{
// 1 2 4 8 16 32 64 ... place-values, reversed here
b *= 2;
}

// sum it up

sum = sum + n * b;

//printf("%d*%d + ",n,b); // uncomment to show the way this works

}
return(sum);
}

About this entry