2 // cencoder.c - c source to a base64 encoding algorithm implementation
4 // This is part of the libb64 project, and has been placed in the public domain.
5 // For details, see http://sourceforge.net/projects/libb64
7 // ** NOTE: MODIFIED BY AJC 2016JAN22 **
8 // The libb64 distribution always places a newline at the end of an encoded block.
9 // We have removed that behavior. If libb64 is updated, make that change again.
13 #include "b64/cencode.h"
15 void base64_init_encodestate(base64_encodestate* state_in)
17 state_in->step = step_A;
21 char base64_encode_value(char value_in)
23 static const char* encoding = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
24 if (value_in > 63) return '=';
25 return encoding[(int)value_in];
28 int base64_encode_block(const char* plaintext_in, int length_in, char* code_out, base64_encodestate* state_in)
30 const char* plainchar = plaintext_in;
31 const char* const plaintextend = plaintext_in + length_in;
32 char* codechar = code_out;
36 result = state_in->result;
38 switch (state_in->step)
43 if (plainchar == plaintextend)
45 state_in->result = result;
46 state_in->step = step_A;
47 return codechar - code_out;
49 fragment = *plainchar++;
50 result = (fragment & 0x0fc) >> 2;
51 *codechar++ = base64_encode_value(result);
52 result = (fragment & 0x003) << 4;
54 if (plainchar == plaintextend)
56 state_in->result = result;
57 state_in->step = step_B;
58 return codechar - code_out;
60 fragment = *plainchar++;
61 result |= (fragment & 0x0f0) >> 4;
62 *codechar++ = base64_encode_value(result);
63 result = (fragment & 0x00f) << 2;
65 if (plainchar == plaintextend)
67 state_in->result = result;
68 state_in->step = step_C;
69 return codechar - code_out;
71 fragment = *plainchar++;
72 result |= (fragment & 0x0c0) >> 6;
73 *codechar++ = base64_encode_value(result);
74 result = (fragment & 0x03f) >> 0;
75 *codechar++ = base64_encode_value(result);
78 /* control should not reach here */
79 return codechar - code_out;
82 int base64_encode_blockend(char* code_out, base64_encodestate* state_in, int with_newline)
84 char* codechar = code_out;
86 switch (state_in->step)
89 *codechar++ = base64_encode_value(state_in->result);
94 *codechar++ = base64_encode_value(state_in->result);
100 if (with_newline) { // added by ajc on 2016jan22, normally citadel doesn't want this
105 return codechar - code_out;