/*************************************** ************************* This is a sample routine of base64 algorithm. The goal is Revoke strate principles, so some details may be ignored. Author Email: zhangwu2003@163.com **************************************** *************************/ # Include <stdio. h> # Include <string. h> # Include <malloc. h> Char * ch64 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789 + /"; Unsigned char * encode (unsigned char * SRC, int srclen) { Int N, buflen, I, j; Int pading = 0; Unsigned char * Buf; Static unsigned char * DST; Buf = SRC; Buflen = n = srclen; If (N % 3! = 0)/* pad with '=' by using a temp buffer */ { Pading = 1; Buflen = N + N % 3; Buf = malloc (buflen + 1 ); Memset (BUF, 0, buflen + 1 ); Memcpy (BUF, SRC, N ); For (I = 0; I <nitrate % 3; I ++) Buf [n + I] = '; } DST = malloc (buflexn * 4/3 + 1 ); Memset (DST, 0, buflen * 4/3 + 1 ); For (I = 0, j = 0; I <buflen; I + = 3, J + = 4) { DST [J] = (BUF [I] & 0xfc)> 2; DST [J + 1] = (BUF [I] & 0x03) <4) + (BUF [I + 1] & 0xf0)> 4 ); DST [J + 2] = (BUF [I + 1] & 0x0f) <2) + (BUF [I + 2] & 0xc0)> 6 ); DST [J + 3] = Buf [I + 2] & 0x3f; } For (I = 0; I <buflen * 4/3; I ++)/* map 6 bit value to base64 ASCII character */ DST [I] = ch64 [DST [I]; If (pading) Free (BUF ); Return DST; } Unsigned char * decode (unsigned char * SRC) { Int N, I, j; Unsigned char * P; Static unsigned char * DST; N = strlen (SRC ); For (I = 0; I <n; I ++)/* map base64 ASCII character to 6 bit value */ { P = strchr (ch64, Src [I]); If (! P) Break; SRC [I] = p-ch64; } DST = malloc (N * 3/4 + 1 ); Memset (DST, 0, N * 3/4 + 1 ); For (I = 0, j = 0; I <n; I + = 4, J + = 3) { DST [J] = (SRC [I] <2) + (SRC [I + 1] & 0x30)> 4 ); DST [J + 1] = (SRC [I + 1] & 0x0f) <4) + (SRC [I + 2] & 0x3c)> 2 ); DST [J + 2] = (SRC [I + 2] & 0x03) <6) + SRC [I + 3]; } Return DST; } Void main () { // Char * src = "zhangwu "; Char SRC [] = {'1', '2', '3', 0, 'A', 'B', '*', 0, 'A ', 'B', '$ '}; Unsigned char * dst1; Unsigned char * dst2; Unsigned int I; Dst1 = encode (SRC, 11);/* The second parameter must accord with the first one */ Printf ("% s/n", dst1 ); Dst2 = decode (dst1 ); For (I = 0; I <_ msize (dst2); I ++) Printf ("% C", dst2 [I]); Free (dst1 ); Free (dst2 ); } |