willy tarreau | 9e13886 | 2006-05-14 23:06:28 +0200 | [diff] [blame] | 1 | /* |
| 2 | * Ascii to Base64 conversion as described in RFC1421. |
| 3 | * Copyright 2006 Willy Tarreau <willy@w.ods.org> |
| 4 | * |
| 5 | * This program is free software; you can redistribute it and/or |
| 6 | * modify it under the terms of the GNU General Public License |
| 7 | * as published by the Free Software Foundation; either version |
| 8 | * 2 of the License, or (at your option) any later version. |
| 9 | * |
| 10 | */ |
| 11 | |
| 12 | #include <include/base64.h> |
| 13 | |
| 14 | |
| 15 | /* Encodes <ilen> bytes from <in> to <out> for at most <olen> chars (including |
| 16 | * the trailing zero). Returns the number of bytes written. No check is made |
| 17 | * for <in> or <out> to be NULL. Returns negative value if <olen> is too short |
| 18 | * to accept <ilen>. 4 output bytes are produced for 1 to 3 input bytes. |
| 19 | */ |
| 20 | int a2base64(char *in, int ilen, char *out, int olen) |
| 21 | { |
| 22 | char base64[64]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; |
| 23 | int convlen; |
| 24 | |
| 25 | convlen = ((ilen + 2) / 3) * 4; |
| 26 | |
| 27 | if (convlen >= olen) |
| 28 | return -1; |
| 29 | |
| 30 | /* we don't need to check olen anymore */ |
| 31 | while (ilen >= 3) { |
| 32 | out[0] = base64[(((unsigned char)in[0]) >> 2)]; |
| 33 | out[1] = base64[(((unsigned char)in[0] & 0x03) << 4) | (((unsigned char)in[1]) >> 4)]; |
| 34 | out[2] = base64[(((unsigned char)in[1] & 0x0F) << 2) | (((unsigned char)in[2]) >> 6)]; |
| 35 | out[3] = base64[(((unsigned char)in[2] & 0x3F))]; |
| 36 | out += 4; |
| 37 | in += 3; ilen -= 3; |
| 38 | } |
| 39 | |
| 40 | if (!ilen) { |
| 41 | out[0] = '\0'; |
| 42 | } else { |
| 43 | out[0] = base64[((unsigned char)in[0]) >> 2]; |
| 44 | if (ilen == 1) { |
| 45 | out[1] = base64[((unsigned char)in[0] & 0x03) << 4]; |
| 46 | out[2] = '='; |
| 47 | } else { |
| 48 | out[1] = base64[(((unsigned char)in[0] & 0x03) << 4) | |
| 49 | (((unsigned char)in[1]) >> 4)]; |
| 50 | out[2] = base64[((unsigned char)in[1] & 0x0F) << 2]; |
| 51 | } |
| 52 | out[3] = '='; |
| 53 | out[4] = '\0'; |
| 54 | } |
| 55 | |
| 56 | return convlen; |
| 57 | } |