libxputty 0.1
Loading...
Searching...
No Matches
b64_encode.c
Go to the documentation of this file.
1
2/* ------------------------------------------------------------------------ *
3 * file: base64_stringencode.c v1.0 *
4 * purpose: tests encoding/decoding strings with base64 *
5 * author: 02/23/2009 Frank4DD *
6 * *
7 * source: http://base64.sourceforge.net/b64.c for encoding *
8 * http://en.literateprograms.org/Base64_(C) for decoding *
9 * ------------------------------------------------------------------------ */
10
11#include <stdio.h>
12#include <string.h>
13
14#include "b64_encode.h"
15
16/* ---- Base64 Encoding/Decoding Table --- */
17char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
18
19/* decodeblock - decode 4 '6-bit' characters into 3 8-bit binary bytes */
20void decodeblock(unsigned char in[], unsigned char **clrstr) {
21 *((*clrstr) ++) = in[0] << 2 | in[1] >> 4;
22 *((*clrstr) ++) = in[1] << 4 | in[2] >> 2;
23 *((*clrstr) ++) = in[2] << 6 | in[3] >> 0;
24}
25
26void b64_decode(char *b64src, char *clrdst) {
27 int c, phase, i;
28 unsigned char in[4];
29 char *p;
30
31 clrdst[0] = '\0';
32 phase = 0;
33 i=0;
34 while(b64src[i]) {
35 c = (int) b64src[i];
36 if(c == '=') {
37 decodeblock(in, (unsigned char **) &clrdst);
38 break;
39 }
40 p = strchr(b64, c);
41 if(p) {
42 in[phase] = p - b64;
43 phase = (phase + 1) % 4;
44 if(phase == 0) {
45 decodeblock(in, (unsigned char **) &clrdst);
46 in[0]=in[1]=in[2]=in[3]=0;
47 }
48 }
49 i++;
50 }
51}
52
53/* encodeblock - encode 3 8-bit binary bytes as 4 '6-bit' characters */
54void encodeblock( unsigned char in[], char b64str[], int len ) {
55 unsigned char out[5];
56 out[0] = b64[ in[0] >> 2 ];
57 out[1] = b64[ ((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4) ];
58 out[2] = (unsigned char) (len > 1 ? b64[ ((in[1] & 0x0f) << 2) |
59 ((in[2] & 0xc0) >> 6) ] : '=');
60 out[3] = (unsigned char) (len > 2 ? b64[ in[2] & 0x3f ] : '=');
61 out[4] = '\0';
62 strncat(b64str, (char*)out, sizeof(char)*5);
63}
64
65/* encode - base64 encode a stream, adding padding if needed */
66void b64_encode(char *clrstr, char *b64dst) {
67 unsigned char in[3];
68 int i, len = 0;
69 int j = 0;
70
71 b64dst[0] = '\0';
72 while(clrstr[j]) {
73 len = 0;
74 for(i=0; i<3; i++) {
75 in[i] = (unsigned char) clrstr[j];
76 if(clrstr[j]) {
77 len++;
78 j++;
79 }
80 else in[i] = 0;
81 }
82 if( len ) {
83 encodeblock( in, b64dst, len );
84 }
85 }
86}
void b64_encode(char *clrstr, char *b64dst)
b64_encode - encode a b64 based char
Definition b64_encode.c:66
void b64_decode(char *b64src, char *clrdst)
b64_decode - decode to a b64 based char
Definition b64_encode.c:26
void encodeblock(unsigned char in[], char b64str[], int len)
Definition b64_encode.c:54
void decodeblock(unsigned char in[], unsigned char **clrstr)
Definition b64_encode.c:20
char b64[]
Definition b64_encode.c:17