Home | History | Annotate | Line # | Download | only in liblutil
base64.c revision 1.1.1.10
      1   1.1.1.9  christos /*	$NetBSD: base64.c,v 1.1.1.10 2025/09/05 21:09:33 christos Exp $	*/
      2   1.1.1.2     lukem 
      3       1.1     lukem /* base64.c -- routines to encode/decode base64 data */
      4   1.1.1.4      tron /* $OpenLDAP$ */
      5       1.1     lukem /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
      6       1.1     lukem  *
      7  1.1.1.10  christos  * Copyright 1998-2024 The OpenLDAP Foundation.
      8       1.1     lukem  * Portions Copyright 1998-2003 Kurt D. Zeilenga.
      9       1.1     lukem  * Portions Copyright 1995 IBM Corporation.
     10       1.1     lukem  * All rights reserved.
     11       1.1     lukem  *
     12       1.1     lukem  * Redistribution and use in source and binary forms, with or without
     13       1.1     lukem  * modification, are permitted only as authorized by the OpenLDAP
     14       1.1     lukem  * Public License.
     15       1.1     lukem  *
     16       1.1     lukem  * A copy of this license is available in the file LICENSE in the
     17       1.1     lukem  * top-level directory of the distribution or, alternatively, at
     18       1.1     lukem  * <http://www.OpenLDAP.org/license.html>.
     19       1.1     lukem  */
     20       1.1     lukem /* Portions Copyright (c) 1996, 1998 by Internet Software Consortium.
     21       1.1     lukem  *
     22       1.1     lukem  * Permission to use, copy, modify, and distribute this software for any
     23       1.1     lukem  * purpose with or without fee is hereby granted, provided that the above
     24       1.1     lukem  * copyright notice and this permission notice appear in all copies.
     25       1.1     lukem  *
     26       1.1     lukem  * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
     27       1.1     lukem  * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
     28       1.1     lukem  * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
     29       1.1     lukem  * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
     30       1.1     lukem  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
     31       1.1     lukem  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
     32       1.1     lukem  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
     33       1.1     lukem  * SOFTWARE.
     34       1.1     lukem  */
     35       1.1     lukem /* This work is based upon Base64 routines (developed by IBM) found
     36       1.1     lukem  * Berkeley Internet Name Daemon (BIND) as distributed by ISC.  They
     37       1.1     lukem  * were adapted for inclusion in OpenLDAP Software by Kurt D. Zeilenga.
     38       1.1     lukem  */
     39       1.1     lukem 
     40   1.1.1.5  christos #include <sys/cdefs.h>
     41   1.1.1.9  christos __RCSID("$NetBSD: base64.c,v 1.1.1.10 2025/09/05 21:09:33 christos Exp $");
     42   1.1.1.5  christos 
     43       1.1     lukem #include "portable.h"
     44       1.1     lukem 
     45       1.1     lukem #include <ac/assert.h>
     46       1.1     lukem #include <ac/stdlib.h>
     47       1.1     lukem #include <ac/ctype.h>
     48       1.1     lukem #include <ac/string.h>
     49       1.1     lukem 
     50       1.1     lukem /* include socket.h to get sys/types.h and/or winsock2.h */
     51       1.1     lukem #include <ac/socket.h>
     52       1.1     lukem 
     53       1.1     lukem #include "lutil.h"
     54       1.1     lukem 
     55       1.1     lukem static const char Base64[] =
     56       1.1     lukem 	"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
     57       1.1     lukem static const char Pad64 = '=';
     58       1.1     lukem 
     59       1.1     lukem /* (From RFC1521 and draft-ietf-dnssec-secext-03.txt)
     60       1.1     lukem    The following encoding technique is taken from RFC 1521 by Borenstein
     61       1.1     lukem    and Freed.  It is reproduced here in a slightly edited form for
     62       1.1     lukem    convenience.
     63       1.1     lukem 
     64       1.1     lukem    A 65-character subset of US-ASCII is used, enabling 6 bits to be
     65       1.1     lukem    represented per printable character. (The extra 65th character, "=",
     66       1.1     lukem    is used to signify a special processing function.)
     67       1.1     lukem 
     68       1.1     lukem    The encoding process represents 24-bit groups of input bits as output
     69       1.1     lukem    strings of 4 encoded characters. Proceeding from left to right, a
     70       1.1     lukem    24-bit input group is formed by concatenating 3 8-bit input groups.
     71       1.1     lukem    These 24 bits are then treated as 4 concatenated 6-bit groups, each
     72       1.1     lukem    of which is translated into a single digit in the base64 alphabet.
     73       1.1     lukem 
     74       1.1     lukem    Each 6-bit group is used as an index into an array of 64 printable
     75       1.1     lukem    characters. The character referenced by the index is placed in the
     76       1.1     lukem    output string.
     77       1.1     lukem 
     78       1.1     lukem                          Table 1: The Base64 Alphabet
     79       1.1     lukem 
     80       1.1     lukem       Value Encoding  Value Encoding  Value Encoding  Value Encoding
     81       1.1     lukem           0 A            17 R            34 i            51 z
     82       1.1     lukem           1 B            18 S            35 j            52 0
     83       1.1     lukem           2 C            19 T            36 k            53 1
     84       1.1     lukem           3 D            20 U            37 l            54 2
     85       1.1     lukem           4 E            21 V            38 m            55 3
     86       1.1     lukem           5 F            22 W            39 n            56 4
     87       1.1     lukem           6 G            23 X            40 o            57 5
     88       1.1     lukem           7 H            24 Y            41 p            58 6
     89       1.1     lukem           8 I            25 Z            42 q            59 7
     90       1.1     lukem           9 J            26 a            43 r            60 8
     91       1.1     lukem          10 K            27 b            44 s            61 9
     92       1.1     lukem          11 L            28 c            45 t            62 +
     93       1.1     lukem          12 M            29 d            46 u            63 /
     94       1.1     lukem          13 N            30 e            47 v
     95       1.1     lukem          14 O            31 f            48 w         (pad) =
     96       1.1     lukem          15 P            32 g            49 x
     97       1.1     lukem          16 Q            33 h            50 y
     98       1.1     lukem 
     99       1.1     lukem    Special processing is performed if fewer than 24 bits are available
    100       1.1     lukem    at the end of the data being encoded.  A full encoding quantum is
    101       1.1     lukem    always completed at the end of a quantity.  When fewer than 24 input
    102       1.1     lukem    bits are available in an input group, zero bits are added (on the
    103       1.1     lukem    right) to form an integral number of 6-bit groups.  Padding at the
    104       1.1     lukem    end of the data is performed using the '=' character.
    105       1.1     lukem 
    106       1.1     lukem    Since all base64 input is an integral number of octets, only the
    107       1.1     lukem          -------------------------------------------------
    108       1.1     lukem    following cases can arise:
    109       1.1     lukem 
    110       1.1     lukem        (1) the final quantum of encoding input is an integral
    111       1.1     lukem            multiple of 24 bits; here, the final unit of encoded
    112       1.1     lukem 	   output will be an integral multiple of 4 characters
    113       1.1     lukem 	   with no "=" padding,
    114       1.1     lukem        (2) the final quantum of encoding input is exactly 8 bits;
    115       1.1     lukem            here, the final unit of encoded output will be two
    116       1.1     lukem 	   characters followed by two "=" padding characters, or
    117       1.1     lukem        (3) the final quantum of encoding input is exactly 16 bits;
    118       1.1     lukem            here, the final unit of encoded output will be three
    119       1.1     lukem 	   characters followed by one "=" padding character.
    120       1.1     lukem    */
    121       1.1     lukem 
    122       1.1     lukem int
    123       1.1     lukem lutil_b64_ntop(
    124  1.1.1.10  christos 	unsigned char const *src,
    125       1.1     lukem 	size_t srclength,
    126       1.1     lukem 	char *target,
    127       1.1     lukem 	size_t targsize)
    128       1.1     lukem {
    129       1.1     lukem 	size_t datalength = 0;
    130  1.1.1.10  christos 	unsigned char input[3];
    131  1.1.1.10  christos 	unsigned char output[4];
    132       1.1     lukem 	size_t i;
    133       1.1     lukem 
    134       1.1     lukem 	while (2 < srclength) {
    135       1.1     lukem 		input[0] = *src++;
    136       1.1     lukem 		input[1] = *src++;
    137       1.1     lukem 		input[2] = *src++;
    138       1.1     lukem 		srclength -= 3;
    139       1.1     lukem 
    140       1.1     lukem 		output[0] = input[0] >> 2;
    141       1.1     lukem 		output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4);
    142       1.1     lukem 		output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6);
    143       1.1     lukem 		output[3] = input[2] & 0x3f;
    144       1.1     lukem 		assert(output[0] < 64);
    145       1.1     lukem 		assert(output[1] < 64);
    146       1.1     lukem 		assert(output[2] < 64);
    147       1.1     lukem 		assert(output[3] < 64);
    148       1.1     lukem 
    149       1.1     lukem 		if (datalength + 4 > targsize)
    150       1.1     lukem 			return (-1);
    151       1.1     lukem 		target[datalength++] = Base64[output[0]];
    152       1.1     lukem 		target[datalength++] = Base64[output[1]];
    153       1.1     lukem 		target[datalength++] = Base64[output[2]];
    154       1.1     lukem 		target[datalength++] = Base64[output[3]];
    155       1.1     lukem 	}
    156       1.1     lukem 
    157       1.1     lukem 	/* Now we worry about padding. */
    158       1.1     lukem 	if (0 != srclength) {
    159       1.1     lukem 		/* Get what's left. */
    160       1.1     lukem 		input[0] = input[1] = input[2] = '\0';
    161       1.1     lukem 		for (i = 0; i < srclength; i++)
    162       1.1     lukem 			input[i] = *src++;
    163       1.1     lukem 
    164       1.1     lukem 		output[0] = input[0] >> 2;
    165       1.1     lukem 		output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4);
    166       1.1     lukem 		output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6);
    167       1.1     lukem 		assert(output[0] < 64);
    168       1.1     lukem 		assert(output[1] < 64);
    169       1.1     lukem 		assert(output[2] < 64);
    170       1.1     lukem 
    171       1.1     lukem 		if (datalength + 4 > targsize)
    172       1.1     lukem 			return (-1);
    173       1.1     lukem 		target[datalength++] = Base64[output[0]];
    174       1.1     lukem 		target[datalength++] = Base64[output[1]];
    175       1.1     lukem 		if (srclength == 1)
    176       1.1     lukem 			target[datalength++] = Pad64;
    177       1.1     lukem 		else
    178       1.1     lukem 			target[datalength++] = Base64[output[2]];
    179       1.1     lukem 		target[datalength++] = Pad64;
    180       1.1     lukem 	}
    181       1.1     lukem 	if (datalength >= targsize)
    182       1.1     lukem 		return (-1);
    183       1.1     lukem 	target[datalength] = '\0';	/* Returned value doesn't count \0. */
    184       1.1     lukem 	return (datalength);
    185       1.1     lukem }
    186       1.1     lukem 
    187       1.1     lukem /* skips all whitespace anywhere.
    188       1.1     lukem    converts characters, four at a time, starting at (or after)
    189       1.1     lukem    src from base - 64 numbers into three 8 bit bytes in the target area.
    190       1.1     lukem    it returns the number of data bytes stored at the target, or -1 on error.
    191       1.1     lukem  */
    192       1.1     lukem 
    193       1.1     lukem int
    194       1.1     lukem lutil_b64_pton(
    195       1.1     lukem 	char const *src,
    196  1.1.1.10  christos 	unsigned char *target,
    197       1.1     lukem 	size_t targsize)
    198       1.1     lukem {
    199       1.1     lukem 	int tarindex, state, ch;
    200       1.1     lukem 	char *pos;
    201       1.1     lukem 
    202       1.1     lukem 	state = 0;
    203       1.1     lukem 	tarindex = 0;
    204       1.1     lukem 
    205       1.1     lukem 	while ((ch = *src++) != '\0') {
    206       1.1     lukem 		if (isascii(ch) && isspace(ch))	/* Skip whitespace anywhere. */
    207       1.1     lukem 			continue;
    208       1.1     lukem 
    209       1.1     lukem 		if (ch == Pad64)
    210       1.1     lukem 			break;
    211       1.1     lukem 
    212       1.1     lukem 		pos = strchr(Base64, ch);
    213       1.1     lukem 		if (pos == 0) 		/* A non-base64 character. */
    214       1.1     lukem 			return (-1);
    215       1.1     lukem 
    216       1.1     lukem 		switch (state) {
    217       1.1     lukem 		case 0:
    218       1.1     lukem 			if (target) {
    219       1.1     lukem 				if ((size_t)tarindex >= targsize)
    220       1.1     lukem 					return (-1);
    221       1.1     lukem 				target[tarindex] = (pos - Base64) << 2;
    222       1.1     lukem 			}
    223       1.1     lukem 			state = 1;
    224       1.1     lukem 			break;
    225       1.1     lukem 		case 1:
    226       1.1     lukem 			if (target) {
    227       1.1     lukem 				if ((size_t)tarindex + 1 >= targsize)
    228       1.1     lukem 					return (-1);
    229       1.1     lukem 				target[tarindex]   |=  (pos - Base64) >> 4;
    230       1.1     lukem 				target[tarindex+1]  = ((pos - Base64) & 0x0f)
    231       1.1     lukem 							<< 4 ;
    232       1.1     lukem 			}
    233       1.1     lukem 			tarindex++;
    234       1.1     lukem 			state = 2;
    235       1.1     lukem 			break;
    236       1.1     lukem 		case 2:
    237       1.1     lukem 			if (target) {
    238       1.1     lukem 				if ((size_t)tarindex + 1 >= targsize)
    239       1.1     lukem 					return (-1);
    240       1.1     lukem 				target[tarindex]   |=  (pos - Base64) >> 2;
    241       1.1     lukem 				target[tarindex+1]  = ((pos - Base64) & 0x03)
    242       1.1     lukem 							<< 6;
    243       1.1     lukem 			}
    244       1.1     lukem 			tarindex++;
    245       1.1     lukem 			state = 3;
    246       1.1     lukem 			break;
    247       1.1     lukem 		case 3:
    248       1.1     lukem 			if (target) {
    249       1.1     lukem 				if ((size_t)tarindex >= targsize)
    250       1.1     lukem 					return (-1);
    251       1.1     lukem 				target[tarindex] |= (pos - Base64);
    252       1.1     lukem 			}
    253       1.1     lukem 			tarindex++;
    254       1.1     lukem 			state = 0;
    255       1.1     lukem 			break;
    256       1.1     lukem 		default:
    257       1.1     lukem 			abort();
    258       1.1     lukem 		}
    259       1.1     lukem 	}
    260       1.1     lukem 
    261       1.1     lukem 	/*
    262       1.1     lukem 	 * We are done decoding Base-64 chars.  Let's see if we ended
    263       1.1     lukem 	 * on a byte boundary, and/or with erroneous trailing characters.
    264       1.1     lukem 	 */
    265       1.1     lukem 
    266       1.1     lukem 	if (ch == Pad64) {		/* We got a pad char. */
    267       1.1     lukem 		ch = *src++;		/* Skip it, get next. */
    268       1.1     lukem 		switch (state) {
    269       1.1     lukem 		case 0:		/* Invalid = in first position */
    270       1.1     lukem 		case 1:		/* Invalid = in second position */
    271       1.1     lukem 			return (-1);
    272       1.1     lukem 
    273       1.1     lukem 		case 2:		/* Valid, means one byte of info */
    274       1.1     lukem 			/* Skip any number of spaces. */
    275       1.1     lukem 			for ((void)NULL; ch != '\0'; ch = *src++)
    276       1.1     lukem 				if (! (isascii(ch) && isspace(ch)))
    277       1.1     lukem 					break;
    278       1.1     lukem 			/* Make sure there is another trailing = sign. */
    279       1.1     lukem 			if (ch != Pad64)
    280       1.1     lukem 				return (-1);
    281       1.1     lukem 			ch = *src++;		/* Skip the = */
    282       1.1     lukem 			/* Fall through to "single trailing =" case. */
    283       1.1     lukem 			/* FALLTHROUGH */
    284       1.1     lukem 
    285       1.1     lukem 		case 3:		/* Valid, means two bytes of info */
    286       1.1     lukem 			/*
    287       1.1     lukem 			 * We know this char is an =.  Is there anything but
    288       1.1     lukem 			 * whitespace after it?
    289       1.1     lukem 			 */
    290       1.1     lukem 			for ((void)NULL; ch != '\0'; ch = *src++)
    291       1.1     lukem 				if (! (isascii(ch) && isspace(ch)))
    292       1.1     lukem 					return (-1);
    293       1.1     lukem 
    294       1.1     lukem 			/*
    295       1.1     lukem 			 * Now make sure for cases 2 and 3 that the "extra"
    296       1.1     lukem 			 * bits that slopped past the last full byte were
    297       1.1     lukem 			 * zeros.  If we don't check them, they become a
    298       1.1     lukem 			 * subliminal channel.
    299       1.1     lukem 			 */
    300       1.1     lukem 			if (target && target[tarindex] != 0)
    301       1.1     lukem 				return (-1);
    302       1.1     lukem 		}
    303       1.1     lukem 	} else {
    304       1.1     lukem 		/*
    305       1.1     lukem 		 * We ended by seeing the end of the string.  Make sure we
    306       1.1     lukem 		 * have no partial bytes lying around.
    307       1.1     lukem 		 */
    308       1.1     lukem 		if (state != 0)
    309       1.1     lukem 			return (-1);
    310       1.1     lukem 	}
    311       1.1     lukem 
    312       1.1     lukem 	return (tarindex);
    313       1.1     lukem }
    314