00001
00020 #include "GKlib.h"
00021
00022 #define B64OFFSET 48
00023
00024
00025
00026
00027
00028 void encodeblock(unsigned char *in, unsigned char *out)
00029 {
00030 out[0] = (in[0] >> 2);
00031 out[1] = (((in[0] & 0x03) << 4) | (in[1] >> 4));
00032 out[2] = (((in[1] & 0x0f) << 2) | (in[2] >> 6));
00033 out[3] = (in[2] & 0x3f);
00034
00035 out[0] += B64OFFSET;
00036 out[1] += B64OFFSET;
00037 out[2] += B64OFFSET;
00038 out[3] += B64OFFSET;
00039
00040
00041 }
00042
00043
00044
00045
00046 void decodeblock(unsigned char *in, unsigned char *out)
00047 {
00048 in[0] -= B64OFFSET;
00049 in[1] -= B64OFFSET;
00050 in[2] -= B64OFFSET;
00051 in[3] -= B64OFFSET;
00052
00053 out[0] = (in[0] << 2 | in[1] >> 4);
00054 out[1] = (in[1] << 4 | in[2] >> 2);
00055 out[2] = (in[2] << 6 | in[3]);
00056 }
00057
00058
00059
00060
00061
00062
00063
00064 void GKEncodeBase64(int nbytes, unsigned char *inbuffer, unsigned char *outbuffer)
00065 {
00066 int i, j;
00067
00068 if (nbytes%3 != 0)
00069 gk_errexit(SIGERR, "GKEncodeBase64: Input buffer size should be a multiple of 3! (%d)\n", nbytes);
00070
00071 for (j=0, i=0; i<nbytes; i+=3, j+=4)
00072 encodeblock(inbuffer+i, outbuffer+j);
00073
00074
00075 outbuffer[j] = '\0';
00076 }
00077
00078
00079
00080
00081
00082
00083
00084
00085 void GKDecodeBase64(int nbytes, unsigned char *inbuffer, unsigned char *outbuffer)
00086 {
00087 int i, j;
00088
00089 if (nbytes%4 != 0)
00090 gk_errexit(SIGERR, "GKDecodeBase64: Input buffer size should be a multiple of 4! (%d)\n", nbytes);
00091
00092 for (j=0, i=0; i<nbytes; i+=4, j+=3)
00093 decodeblock(inbuffer+i, outbuffer+j);
00094 }
00095