A
download base64.c
Language: C
LOC: 69
Project Info
efone
Server: SourceForge
Type: cvs
...e\efone\efone\efone\crypto\
   base64.c
   global.h
   hmac_md5.c
   hmac_md5.h
   md5.c
   md5.h

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

unsigned char *base64_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

int unbase64(int ch)
{
  int i;
  if (ch == '=') return 0;
  for (i = 0; i < 64; i++)
    if (ch == base64_alphabet[i])
      return i;
  return 0;
}

int base64_decode(char *str,char *dst,int len)
{
  int i, j, l;
  unsigned char input[4], output[3];

  if (str == 0)
    return 0;
  l = strlen(str);
  if (dst == 0 || l > len)
    return (l / 4) * 3;
  memset(dst,0,len);
  for (i=j=0; i<l; i +=4) {
    input[0] = unbase64(str[i]);
    input[1] = unbase64(str[i+1]);
    input[2] = unbase64(str[i+2]);
    input[3] = unbase64(str[i+3]);
    output[0] = (input[0] << 2) | (input[1] >> 4);
    output[1] = (input[1] << 4) | (input[2] >> 2);
    output[2] = (input[2] << 6) | (input[3]);
    dst[j] = output[0];
    if (str[i+1] == '=') return j+1;
    dst[j+1]=output[1];
    if (str[i+2] == '=') return j+2;
    dst[j+2]=output[2];
    j += 3;
  }
  return j;
}

char *base64_encode(char *input, int inplen)
{
int	a=0,b=0,c=0;
int	i, j;
int	d, e, f, g;
int 	outlen=4;
static char 	*output=NULL;

	/* if (inplen)	return;
	 * Uhm, if we have input, return? What the fuck */

	for (j=i=0; i< inplen ; i += 3)
	{
		a=input[i];
		b= i+1 < inplen ? input[i+1]:0;
		c= i+2 < inplen ? input[i+2]:0;

		d=base64_alphabet[ a >> 2 ];
		e=base64_alphabet[ ((a & 3 ) << 4) | (b >> 4)];
		f=base64_alphabet[ ((b & 15) << 2) | (c >> 6)];
		g=base64_alphabet[ c & 63 ];
		if (i + 1 >= inplen) f='=';
		if (i + 2 >= inplen) g='=';
		output=realloc(output, outlen);
		output[outlen-4]=d;
		output[outlen-3]=e;
		output[outlen-2]=f;
		output[outlen-1]=g;
		outlen+=4;
	}
	output=realloc(output,outlen-3);
	output[outlen-4] = '\0';
	return output;
	/* this is a statically allocated string.  Make sure and dup it
	 * if you need to save it between calls.  This entire algorithm
	 * seems memory-kludy though */
}

About Koders | Resources | Downloads | Support | Black Duck | Submit Project | Terms of Service | DMCA | Privacy Policy | Site Map| Contact Us