blob: a427d5d8373e924a7d9657ed76ae17905ac7dacd [file] [log] [blame]
willy tarreau9e138862006-05-14 23:06:28 +02001/*
2 * Ascii to Base64 conversion as described in RFC1421.
Willy Tarreaubaaee002006-06-26 02:48:02 +02003 *
4 * Copyright 2006 Willy Tarreau <w@1wt.eu>
willy tarreau9e138862006-05-14 23:06:28 +02005 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Willy Tarreaubaaee002006-06-26 02:48:02 +020013#include <haproxy/base64.h>
willy tarreau9e138862006-05-14 23:06:28 +020014
Willy Tarreaubaaee002006-06-26 02:48:02 +020015const char base64tab[64]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
willy tarreau9e138862006-05-14 23:06:28 +020016
17/* Encodes <ilen> bytes from <in> to <out> for at most <olen> chars (including
18 * the trailing zero). Returns the number of bytes written. No check is made
19 * for <in> or <out> to be NULL. Returns negative value if <olen> is too short
20 * to accept <ilen>. 4 output bytes are produced for 1 to 3 input bytes.
21 */
22int a2base64(char *in, int ilen, char *out, int olen)
23{
willy tarreau9e138862006-05-14 23:06:28 +020024 int convlen;
25
26 convlen = ((ilen + 2) / 3) * 4;
27
28 if (convlen >= olen)
29 return -1;
30
31 /* we don't need to check olen anymore */
32 while (ilen >= 3) {
Willy Tarreaubaaee002006-06-26 02:48:02 +020033 out[0] = base64tab[(((unsigned char)in[0]) >> 2)];
34 out[1] = base64tab[(((unsigned char)in[0] & 0x03) << 4) | (((unsigned char)in[1]) >> 4)];
35 out[2] = base64tab[(((unsigned char)in[1] & 0x0F) << 2) | (((unsigned char)in[2]) >> 6)];
36 out[3] = base64tab[(((unsigned char)in[2] & 0x3F))];
willy tarreau9e138862006-05-14 23:06:28 +020037 out += 4;
38 in += 3; ilen -= 3;
39 }
40
41 if (!ilen) {
42 out[0] = '\0';
43 } else {
Willy Tarreaubaaee002006-06-26 02:48:02 +020044 out[0] = base64tab[((unsigned char)in[0]) >> 2];
willy tarreau9e138862006-05-14 23:06:28 +020045 if (ilen == 1) {
Willy Tarreaubaaee002006-06-26 02:48:02 +020046 out[1] = base64tab[((unsigned char)in[0] & 0x03) << 4];
willy tarreau9e138862006-05-14 23:06:28 +020047 out[2] = '=';
48 } else {
Willy Tarreaubaaee002006-06-26 02:48:02 +020049 out[1] = base64tab[(((unsigned char)in[0] & 0x03) << 4) |
willy tarreau9e138862006-05-14 23:06:28 +020050 (((unsigned char)in[1]) >> 4)];
Willy Tarreaubaaee002006-06-26 02:48:02 +020051 out[2] = base64tab[((unsigned char)in[1] & 0x0F) << 2];
willy tarreau9e138862006-05-14 23:06:28 +020052 }
53 out[3] = '=';
54 out[4] = '\0';
55 }
56
57 return convlen;
58}