]>
git.ipfire.org Git - thirdparty/squid.git/blob - lib/base64.c
2 * $Id: base64.c,v 1.19 2001/06/29 20:20:01 wessels Exp $
16 static void base64_init(void);
18 static int base64_initialized
= 0;
19 #define BASE64_VALUE_SZ 256
20 #define BASE64_RESULT_SZ 8192
21 int base64_value
[BASE64_VALUE_SZ
];
22 const char base64_code
[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
30 for (i
= 0; i
< BASE64_VALUE_SZ
; i
++)
33 for (i
= 0; i
< 64; i
++)
34 base64_value
[(int) base64_code
[i
]] = i
;
35 base64_value
['='] = 0;
37 base64_initialized
= 1;
41 base64_decode(const char *p
)
43 static char result
[BASE64_RESULT_SZ
];
49 if (!base64_initialized
)
52 for (j
= 0; *p
&& j
+ 4 < BASE64_RESULT_SZ
; p
++) {
53 unsigned int k
= ((unsigned char) *p
) % BASE64_VALUE_SZ
;
54 if (base64_value
[k
] < 0)
57 val
+= base64_value
[k
];
60 /* One quantum of four encoding characters/24 bit */
61 result
[j
++] = val
>> 16; /* High 8 bits */
62 result
[j
++] = (val
>> 8) & 0xff; /* Mid 8 bits */
63 result
[j
++] = val
& 0xff; /* Low 8 bits */
70 /* adopted from http://ftp.sunet.se/pub2/gnu/vm/base64-encode.c with adjustments */
72 base64_encode(const char *decoded_str
)
74 static char result
[BASE64_RESULT_SZ
];
83 if (!base64_initialized
)
86 while ((c
= (unsigned char) *decoded_str
++) && out_cnt
< sizeof(result
) - 5) {
89 if (char_count
== 3) {
90 result
[out_cnt
++] = base64_code
[bits
>> 18];
91 result
[out_cnt
++] = base64_code
[(bits
>> 12) & 0x3f];
92 result
[out_cnt
++] = base64_code
[(bits
>> 6) & 0x3f];
93 result
[out_cnt
++] = base64_code
[bits
& 0x3f];
100 if (char_count
!= 0) {
101 bits
<<= 16 - (8 * char_count
);
102 result
[out_cnt
++] = base64_code
[bits
>> 18];
103 result
[out_cnt
++] = base64_code
[(bits
>> 12) & 0x3f];
104 if (char_count
== 1) {
105 result
[out_cnt
++] = '=';
106 result
[out_cnt
++] = '=';
108 result
[out_cnt
++] = base64_code
[(bits
>> 6) & 0x3f];
109 result
[out_cnt
++] = '=';
112 result
[out_cnt
] = '\0'; /* terminate */
116 /* adopted from http://ftp.sunet.se/pub2/gnu/vm/base64-encode.c with adjustments */
118 base64_encode_bin(const char *data
, int len
)
120 static char result
[BASE64_RESULT_SZ
];
128 if (!base64_initialized
)
131 while (len
-- && out_cnt
< sizeof(result
) - 5) {
132 int c
= (unsigned char) *data
++;
135 if (char_count
== 3) {
136 result
[out_cnt
++] = base64_code
[bits
>> 18];
137 result
[out_cnt
++] = base64_code
[(bits
>> 12) & 0x3f];
138 result
[out_cnt
++] = base64_code
[(bits
>> 6) & 0x3f];
139 result
[out_cnt
++] = base64_code
[bits
& 0x3f];
146 if (char_count
!= 0) {
147 bits
<<= 16 - (8 * char_count
);
148 result
[out_cnt
++] = base64_code
[bits
>> 18];
149 result
[out_cnt
++] = base64_code
[(bits
>> 12) & 0x3f];
150 if (char_count
== 1) {
151 result
[out_cnt
++] = '=';
152 result
[out_cnt
++] = '=';
154 result
[out_cnt
++] = base64_code
[(bits
>> 6) & 0x3f];
155 result
[out_cnt
++] = '=';
158 result
[out_cnt
] = '\0'; /* terminate */