base64.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /*
  2. * base64 - libubox base64 functions
  3. *
  4. * Copyright (C) 2015 Felix Fietkau <nbd@openwrt.org>
  5. *
  6. * Permission to use, copy, modify, and/or distribute this software for any
  7. * purpose with or without fee is hereby granted, provided that the above
  8. * copyright notice and this permission notice appear in all copies.
  9. *
  10. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  11. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  12. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  13. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  14. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  15. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  16. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  17. */
  18. /* $OpenBSD: base64.c,v 1.7 2013/12/31 02:32:56 tedu Exp $ */
  19. /*
  20. * Copyright (c) 1996 by Internet Software Consortium.
  21. *
  22. * Permission to use, copy, modify, and distribute this software for any
  23. * purpose with or without fee is hereby granted, provided that the above
  24. * copyright notice and this permission notice appear in all copies.
  25. *
  26. * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
  27. * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
  28. * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
  29. * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  30. * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  31. * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
  32. * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
  33. * SOFTWARE.
  34. */
  35. /*
  36. * Portions Copyright (c) 1995 by International Business Machines, Inc.
  37. *
  38. * International Business Machines, Inc. (hereinafter called IBM) grants
  39. * permission under its copyrights to use, copy, modify, and distribute this
  40. * Software with or without fee, provided that the above copyright notice and
  41. * all paragraphs of this notice appear in all copies, and that the name of IBM
  42. * not be used in connection with the marketing of any product incorporating
  43. * the Software or modifications thereof, without specific, written prior
  44. * permission.
  45. *
  46. * To the extent it has a right to do so, IBM grants an immunity from suit
  47. * under its patents, if any, for the use, sale or manufacture of products to
  48. * the extent that such products are used for performing Domain Name System
  49. * dynamic updates in TCP/IP networks by means of the Software. No immunity is
  50. * granted for any product per se or for any other function of any product.
  51. *
  52. * THE SOFTWARE IS PROVIDED "AS IS", AND IBM DISCLAIMS ALL WARRANTIES,
  53. * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  54. * PARTICULAR PURPOSE. IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL,
  55. * DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER ARISING
  56. * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE, EVEN
  57. * IF IBM IS APPRISED OF THE POSSIBILITY OF SUCH DAMAGES.
  58. */
  59. #include <sys/types.h>
  60. #include <ctype.h>
  61. #include <stdio.h>
  62. #include <stdlib.h>
  63. #include <string.h>
  64. #include "assert.h"
  65. #include "utils.h"
  66. static const char Base64[] =
  67. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  68. static const char Pad64 = '=';
  69. /* (From RFC1521 and draft-ietf-dnssec-secext-03.txt)
  70. The following encoding technique is taken from RFC 1521 by Borenstein
  71. and Freed. It is reproduced here in a slightly edited form for
  72. convenience.
  73. A 65-character subset of US-ASCII is used, enabling 6 bits to be
  74. represented per printable character. (The extra 65th character, "=",
  75. is used to signify a special processing function.)
  76. The encoding process represents 24-bit groups of input bits as output
  77. strings of 4 encoded characters. Proceeding from left to right, a
  78. 24-bit input group is formed by concatenating 3 8-bit input groups.
  79. These 24 bits are then treated as 4 concatenated 6-bit groups, each
  80. of which is translated into a single digit in the base64 alphabet.
  81. Each 6-bit group is used as an index into an array of 64 printable
  82. characters. The character referenced by the index is placed in the
  83. output string.
  84. Table 1: The Base64 Alphabet
  85. Value Encoding Value Encoding Value Encoding Value Encoding
  86. 0 A 17 R 34 i 51 z
  87. 1 B 18 S 35 j 52 0
  88. 2 C 19 T 36 k 53 1
  89. 3 D 20 U 37 l 54 2
  90. 4 E 21 V 38 m 55 3
  91. 5 F 22 W 39 n 56 4
  92. 6 G 23 X 40 o 57 5
  93. 7 H 24 Y 41 p 58 6
  94. 8 I 25 Z 42 q 59 7
  95. 9 J 26 a 43 r 60 8
  96. 10 K 27 b 44 s 61 9
  97. 11 L 28 c 45 t 62 +
  98. 12 M 29 d 46 u 63 /
  99. 13 N 30 e 47 v
  100. 14 O 31 f 48 w (pad) =
  101. 15 P 32 g 49 x
  102. 16 Q 33 h 50 y
  103. Special processing is performed if fewer than 24 bits are available
  104. at the end of the data being encoded. A full encoding quantum is
  105. always completed at the end of a quantity. When fewer than 24 input
  106. bits are available in an input group, zero bits are added (on the
  107. right) to form an integral number of 6-bit groups. Padding at the
  108. end of the data is performed using the '=' character.
  109. Since all base64 input is an integral number of octets, only the
  110. -------------------------------------------------
  111. following cases can arise:
  112. (1) the final quantum of encoding input is an integral
  113. multiple of 24 bits; here, the final unit of encoded
  114. output will be an integral multiple of 4 characters
  115. with no "=" padding,
  116. (2) the final quantum of encoding input is exactly 8 bits;
  117. here, the final unit of encoded output will be two
  118. characters followed by two "=" padding characters, or
  119. (3) the final quantum of encoding input is exactly 16 bits;
  120. here, the final unit of encoded output will be three
  121. characters followed by one "=" padding character.
  122. */
  123. int b64_encode(const void *_src, size_t srclength,
  124. void *dest, size_t targsize)
  125. {
  126. const unsigned char *src = _src;
  127. char *target = dest;
  128. size_t datalength = 0;
  129. u_char input[3] = {0};
  130. u_char output[4];
  131. size_t i;
  132. assert(dest && targsize > 0);
  133. while (2 < srclength) {
  134. input[0] = *src++;
  135. input[1] = *src++;
  136. input[2] = *src++;
  137. srclength -= 3;
  138. output[0] = input[0] >> 2;
  139. output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4);
  140. output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6);
  141. output[3] = input[2] & 0x3f;
  142. if (datalength + 4 > targsize)
  143. return (-1);
  144. target[datalength++] = Base64[output[0]];
  145. target[datalength++] = Base64[output[1]];
  146. target[datalength++] = Base64[output[2]];
  147. target[datalength++] = Base64[output[3]];
  148. }
  149. /* Now we worry about padding. */
  150. if (0 != srclength) {
  151. /* Get what's left. */
  152. input[0] = input[1] = input[2] = '\0';
  153. for (i = 0; i < srclength; i++)
  154. input[i] = *src++;
  155. output[0] = input[0] >> 2;
  156. output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4);
  157. output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6);
  158. if (datalength + 4 > targsize)
  159. return (-1);
  160. target[datalength++] = Base64[output[0]];
  161. target[datalength++] = Base64[output[1]];
  162. if (srclength == 1)
  163. target[datalength++] = Pad64;
  164. else
  165. target[datalength++] = Base64[output[2]];
  166. target[datalength++] = Pad64;
  167. }
  168. if (datalength >= targsize)
  169. return (-1);
  170. target[datalength] = '\0'; /* Returned value doesn't count \0. */
  171. return (datalength);
  172. }
  173. /* skips all whitespace anywhere.
  174. converts characters, four at a time, starting at (or after)
  175. src from base - 64 numbers into three 8 bit bytes in the target area.
  176. it returns the number of data bytes stored at the target, or -1 on error.
  177. */
  178. int b64_decode(const void *_src, void *dest, size_t targsize)
  179. {
  180. const char *src = _src;
  181. unsigned char *target = dest;
  182. int state, ch;
  183. size_t tarindex;
  184. u_char nextbyte;
  185. char *pos;
  186. state = 0;
  187. tarindex = 0;
  188. assert(dest && targsize > 0);
  189. while ((ch = (unsigned char)*src++) != '\0') {
  190. if (isspace(ch)) /* Skip whitespace anywhere. */
  191. continue;
  192. if (ch == Pad64)
  193. break;
  194. pos = strchr(Base64, ch);
  195. if (pos == 0) /* A non-base64 character. */
  196. return (-1);
  197. switch (state) {
  198. case 0:
  199. if (target) {
  200. if (tarindex >= targsize)
  201. return (-1);
  202. target[tarindex] = (pos - Base64) << 2;
  203. }
  204. state = 1;
  205. break;
  206. case 1:
  207. if (target) {
  208. if (tarindex >= targsize)
  209. return (-1);
  210. target[tarindex] |= (pos - Base64) >> 4;
  211. nextbyte = ((pos - Base64) & 0x0f) << 4;
  212. if (tarindex + 1 < targsize)
  213. target[tarindex+1] = nextbyte;
  214. else if (nextbyte)
  215. return (-1);
  216. }
  217. tarindex++;
  218. state = 2;
  219. break;
  220. case 2:
  221. if (target) {
  222. if (tarindex >= targsize)
  223. return (-1);
  224. target[tarindex] |= (pos - Base64) >> 2;
  225. nextbyte = ((pos - Base64) & 0x03) << 6;
  226. if (tarindex + 1 < targsize)
  227. target[tarindex+1] = nextbyte;
  228. else if (nextbyte)
  229. return (-1);
  230. }
  231. tarindex++;
  232. state = 3;
  233. break;
  234. case 3:
  235. if (target) {
  236. if (tarindex >= targsize)
  237. return (-1);
  238. target[tarindex] |= (pos - Base64);
  239. }
  240. tarindex++;
  241. state = 0;
  242. break;
  243. }
  244. }
  245. /*
  246. * We are done decoding Base-64 chars. Let's see if we ended
  247. * on a byte boundary, and/or with erroneous trailing characters.
  248. */
  249. if (ch == Pad64) { /* We got a pad char. */
  250. ch = (unsigned char)*src++; /* Skip it, get next. */
  251. switch (state) {
  252. case 0: /* Invalid = in first position */
  253. case 1: /* Invalid = in second position */
  254. return (-1);
  255. case 2: /* Valid, means one byte of info */
  256. /* Skip any number of spaces. */
  257. for (; ch != '\0'; ch = (unsigned char)*src++)
  258. if (!isspace(ch))
  259. break;
  260. /* Make sure there is another trailing = sign. */
  261. if (ch != Pad64)
  262. return (-1);
  263. ch = (unsigned char)*src++; /* Skip the = */
  264. /* Fall through to "single trailing =" case. */
  265. /* FALLTHROUGH */
  266. case 3: /* Valid, means two bytes of info */
  267. /*
  268. * We know this char is an =. Is there anything but
  269. * whitespace after it?
  270. */
  271. for (; ch != '\0'; ch = (unsigned char)*src++)
  272. if (!isspace(ch))
  273. return (-1);
  274. /*
  275. * Now make sure for cases 2 and 3 that the "extra"
  276. * bits that slopped past the last full byte were
  277. * zeros. If we don't check them, they become a
  278. * subliminal channel.
  279. */
  280. if (target && tarindex < targsize &&
  281. target[tarindex] != 0)
  282. return (-1);
  283. }
  284. } else {
  285. /*
  286. * We ended by seeing the end of the string. Make sure we
  287. * have no partial bytes lying around.
  288. */
  289. if (state != 0)
  290. return (-1);
  291. }
  292. /* Null-terminate if we have room left */
  293. if (tarindex < targsize)
  294. target[tarindex] = 0;
  295. return (tarindex);
  296. }