VirtualBox

source: vbox/trunk/src/VBox/Runtime/common/string/base64.cpp@ 42599

Last change on this file since 42599 was 40058, checked in by vboxsync, 13 years ago

RTBase64: fix trailing newline suppression in RTBase64EncodedLength, plus testcase

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 16.6 KB
Line 
1/* $Id: base64.cpp 40058 2012-02-10 13:10:26Z vboxsync $ */
2/** @file
3 * IPRT - Base64, MIME content transfer encoding.
4 */
5
6/*
7 * Copyright (C) 2009 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*******************************************************************************
29* Header Files *
30*******************************************************************************/
31#include <iprt/base64.h>
32#include "internal/iprt.h"
33
34#include <iprt/assert.h>
35#include <iprt/err.h>
36#include <iprt/ctype.h>
37#ifdef RT_STRICT
38# include <iprt/asm.h>
39#endif
40
41
42/*******************************************************************************
43* Defined Constants And Macros *
44*******************************************************************************/
45/** The line length used for encoding. */
46#define RTBASE64_LINE_LEN 64
47
48/** @name Special g_au8CharToVal values
49 * @{ */
50#define BASE64_SPACE 0xc0
51#define BASE64_PAD 0xe0
52#define BASE64_INVALID 0xff
53/** @} */
54
55
56/*******************************************************************************
57* Global Variables *
58*******************************************************************************/
59/** Base64 character to value. (RFC 2045)
60 * ASSUMES ASCII / UTF-8. */
61static const uint8_t g_au8CharToVal[256] =
62{
63 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xff, 0xff, /* 0x00..0x0f */
64 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x10..0x1f */
65 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 62, 0xff, 0xff, 0xff, 63, /* 0x20..0x2f */
66 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0xff, 0xff, 0xff, 0xe0, 0xff, 0xff, /* 0x30..0x3f */
67 0xff, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 0x40..0x4f */
68 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x50..0x5f */
69 0xff, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 0x60..0x6f */
70 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x70..0x7f */
71 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x80..0x8f */
72 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x90..0x9f */
73 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xa0..0xaf */
74 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xb0..0xbf */
75 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xc0..0xcf */
76 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xd0..0xdf */
77 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xe0..0xef */
78 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff /* 0xf0..0xff */
79};
80
81/** Value to Base64 character. (RFC 2045) */
82static const char g_szValToChar[64+1] =
83 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
84
85
86#ifdef RT_STRICT
87/**
88 * Perform table sanity checks on the first call.
89 */
90static void rtBase64Sanity(void)
91{
92 static bool s_fSane = false;
93 if (RT_UNLIKELY(!s_fSane))
94 {
95 for (unsigned i = 0; i < 64; i++)
96 {
97 unsigned ch = g_szValToChar[i];
98 Assert(ch);
99 Assert(g_au8CharToVal[ch] == i);
100 }
101
102 for (unsigned i = 0; i < 256; i++)
103 {
104 uint8_t u8 = g_au8CharToVal[i];
105 Assert( ( u8 == BASE64_INVALID
106 && !RT_C_IS_ALNUM(i)
107 && !RT_C_IS_SPACE(i))
108 || ( u8 == BASE64_PAD
109 && i == '=')
110 || ( u8 == BASE64_SPACE
111 && ( RT_C_IS_SPACE(i)
112 || (i == '\r'))) /* Carriage return is handled as a space character as well. */
113 || ( u8 < 64
114 && (unsigned)g_szValToChar[u8] == i));
115 }
116 ASMAtomicWriteBool(&s_fSane, true);
117 }
118}
119#endif /* RT_STRICT */
120
121
122/**
123 * Calculates the decoded data size for a Base64 encoded string.
124 *
125 * @returns The length in bytes. -1 if the encoding is bad.
126 *
127 * @param pszString The Base64 encoded string.
128 * @param ppszEnd If not NULL, this will point to the first char
129 * following the Base64 encoded text block. If
130 * NULL the entire string is assumed to be Base64.
131 */
132RTDECL(ssize_t) RTBase64DecodedSize(const char *pszString, char **ppszEnd)
133{
134#ifdef RT_STRICT
135 rtBase64Sanity();
136#endif
137
138 /*
139 * Walk the string until a non-encoded or non-space character is encountered.
140 */
141 uint32_t c6Bits = 0;
142 uint8_t u8 = BASE64_INVALID;
143 unsigned ch;
144 AssertCompile(sizeof(char) == sizeof(uint8_t));
145
146 while ((ch = *pszString))
147 {
148 u8 = g_au8CharToVal[ch];
149 if (u8 < 64)
150 c6Bits++;
151 else if (RT_UNLIKELY(u8 != BASE64_SPACE))
152 break;
153
154 /* advance */
155 pszString++;
156 }
157
158 /*
159 * Padding can only be found at the end and there is
160 * only 1 or 2 padding chars. Deal with it first.
161 */
162 unsigned cbPad = 0;
163 if (u8 == BASE64_PAD)
164 {
165 cbPad = 1;
166 c6Bits++;
167 pszString++;
168 while ((ch = *pszString))
169 {
170 u8 = g_au8CharToVal[ch];
171 if (u8 != BASE64_SPACE)
172 {
173 if (u8 != BASE64_PAD)
174 break;
175 c6Bits++;
176 cbPad++;
177 }
178 pszString++;
179 }
180 if (cbPad >= 3)
181 return -1;
182 }
183
184 /*
185 * Invalid char and no where to indicate where the
186 * Base64 text ends? Return failure.
187 */
188 if ( u8 == BASE64_INVALID
189 && !ppszEnd
190 && ch)
191 return -1;
192
193 /*
194 * Recalc 6-bit to 8-bit and adjust for padding.
195 */
196 size_t cb;
197 if (c6Bits * 3 / 3 == c6Bits)
198 {
199 if ((c6Bits * 3 % 4) != 0)
200 return -1;
201 cb = c6Bits * 3 / 4;
202 }
203 else
204 {
205 if ((c6Bits * (uint64_t)3 % 4) != 0)
206 return -1;
207 cb = c6Bits * (uint64_t)3 / 4;
208 }
209
210 if (cb < cbPad)
211 return -1;
212 cb -= cbPad;
213
214 if (ppszEnd)
215 *ppszEnd = (char *)pszString;
216 return cb;
217}
218RT_EXPORT_SYMBOL(RTBase64DecodedSize);
219
220
221/**
222 * Decodes a Base64 encoded string into the buffer supplied by the caller.
223 *
224 * @returns IPRT status code.
225 * @retval VERR_BUFFER_OVERFLOW if the buffer is too small. pcbActual will not
226 * be set, nor will ppszEnd.
227 * @retval VERR_INVALID_BASE64_ENCODING if the encoding is wrong.
228 *
229 * @param pszString The Base64 string. Whether the entire string or
230 * just the start of the string is in Base64 depends
231 * on whether ppszEnd is specified or not.
232 * @param pvData Where to store the decoded data.
233 * @param cbData The size of the output buffer that pvData points to.
234 * @param pcbActual Where to store the actual number of bytes returned.
235 * Optional.
236 * @param ppszEnd Indicates that the string may contain other stuff
237 * after the Base64 encoded data when not NULL. Will
238 * be set to point to the first char that's not part of
239 * the encoding. If NULL the entire string must be part
240 * of the Base64 encoded data.
241 */
242RTDECL(int) RTBase64Decode(const char *pszString, void *pvData, size_t cbData, size_t *pcbActual, char **ppszEnd)
243{
244#ifdef RT_STRICT
245 rtBase64Sanity();
246#endif
247
248 /*
249 * Process input in groups of 4 input / 3 output chars.
250 */
251 uint8_t u8Trio[3] = { 0, 0, 0 }; /* shuts up gcc */
252 uint8_t *pbData = (uint8_t *)pvData;
253 uint8_t u8 = BASE64_INVALID;
254 unsigned c6Bits = 0;
255 unsigned ch;
256 AssertCompile(sizeof(char) == sizeof(uint8_t));
257
258 for (;;)
259 {
260 /* The first 6-bit group. */
261 while ((u8 = g_au8CharToVal[ch = *pszString]) == BASE64_SPACE)
262 pszString++;
263 if (u8 >= 64)
264 {
265 c6Bits = 0;
266 break;
267 }
268 u8Trio[0] = u8 << 2;
269 pszString++;
270
271 /* The second 6-bit group. */
272 while ((u8 = g_au8CharToVal[ch = *pszString]) == BASE64_SPACE)
273 pszString++;
274 if (u8 >= 64)
275 {
276 c6Bits = 1;
277 break;
278 }
279 u8Trio[0] |= u8 >> 4;
280 u8Trio[1] = u8 << 4;
281 pszString++;
282
283 /* The third 6-bit group. */
284 while ((u8 = g_au8CharToVal[ch = *pszString]) == BASE64_SPACE)
285 pszString++;
286 if (u8 >= 64)
287 {
288 c6Bits = 2;
289 break;
290 }
291 u8Trio[1] |= u8 >> 2;
292 u8Trio[2] = u8 << 6;
293 pszString++;
294
295 /* The fourth 6-bit group. */
296 while ((u8 = g_au8CharToVal[ch = *pszString]) == BASE64_SPACE)
297 pszString++;
298 if (u8 >= 64)
299 {
300 c6Bits = 3;
301 break;
302 }
303 u8Trio[2] |= u8;
304 pszString++;
305
306 /* flush the trio */
307 if (cbData < 3)
308 return VERR_BUFFER_OVERFLOW;
309 cbData -= 3;
310 pbData[0] = u8Trio[0];
311 pbData[1] = u8Trio[1];
312 pbData[2] = u8Trio[2];
313 pbData += 3;
314 }
315
316 /*
317 * Padding can only be found at the end and there is
318 * only 1 or 2 padding chars. Deal with it first.
319 */
320 unsigned cbPad = 0;
321 if (u8 == BASE64_PAD)
322 {
323 cbPad = 1;
324 pszString++;
325 while ((ch = *pszString))
326 {
327 u8 = g_au8CharToVal[ch];
328 if (u8 != BASE64_SPACE)
329 {
330 if (u8 != BASE64_PAD)
331 break;
332 cbPad++;
333 }
334 pszString++;
335 }
336 if (cbPad >= 3)
337 return VERR_INVALID_BASE64_ENCODING;
338 }
339
340 /*
341 * Invalid char and no where to indicate where the
342 * Base64 text ends? Return failure.
343 */
344 if ( u8 == BASE64_INVALID
345 && !ppszEnd
346 && ch)
347 return VERR_INVALID_BASE64_ENCODING;
348
349 /*
350 * Check padding vs. pending sextets, if anything left to do finish it off.
351 */
352 if (c6Bits || cbPad)
353 {
354 if (c6Bits + cbPad != 4)
355 return VERR_INVALID_BASE64_ENCODING;
356
357 switch (c6Bits)
358 {
359 case 1:
360 u8Trio[1] = u8Trio[2] = 0;
361 break;
362 case 2:
363 u8Trio[2] = 0;
364 break;
365 case 3:
366 default:
367 break;
368 }
369 switch (3 - cbPad)
370 {
371 case 1:
372 if (cbData < 1)
373 return VERR_BUFFER_OVERFLOW;
374 cbData--;
375 pbData[0] = u8Trio[0];
376 pbData++;
377 break;
378
379 case 2:
380 if (cbData < 2)
381 return VERR_BUFFER_OVERFLOW;
382 cbData -= 2;
383 pbData[0] = u8Trio[0];
384 pbData[1] = u8Trio[1];
385 pbData += 2;
386 break;
387
388 default:
389 break;
390 }
391 }
392
393 /*
394 * Set optional return values and return successfully.
395 */
396 if (ppszEnd)
397 *ppszEnd = (char *)pszString;
398 if (pcbActual)
399 *pcbActual = pbData - (uint8_t *)pvData;
400 return VINF_SUCCESS;
401}
402RT_EXPORT_SYMBOL(RTBase64Decode);
403
404
405/**
406 * Calculates the length of the Base64 encoding of a given number of bytes of
407 * data.
408 *
409 * This will assume line breaks every 64 chars. A RTBase64EncodedLengthEx
410 * function can be added if closer control over the output is found to be
411 * required.
412 *
413 * @returns The Base64 string length.
414 * @param cbData The number of bytes to encode.
415 */
416RTDECL(size_t) RTBase64EncodedLength(size_t cbData)
417{
418 if (cbData * 8 / 8 != cbData)
419 {
420 AssertReturn(sizeof(size_t) == sizeof(uint64_t), ~(size_t)0);
421 uint64_t cch = cbData * (uint64_t)8;
422 while (cch % 24)
423 cch += 8;
424 cch /= 6;
425
426 cch += ((cch - 1) / RTBASE64_LINE_LEN) * RTBASE64_EOL_SIZE;
427 return cch;
428 }
429
430 size_t cch = cbData * 8;
431 while (cch % 24)
432 cch += 8;
433 cch /= 6;
434
435 cch += ((cch - 1) / RTBASE64_LINE_LEN) * RTBASE64_EOL_SIZE;
436 return cch;
437}
438RT_EXPORT_SYMBOL(RTBase64EncodedLength);
439
440
441/**
442 * Encodes the specifed data into a Base64 string, the caller supplies the
443 * output buffer.
444 *
445 * This will make the same assumptions about line breaks and EOL size as
446 * RTBase64EncodedLength() does. A RTBase64EncodeEx function can be added if
447 * more strict control over the output formatting is found necessary.
448 *
449 * @returns IRPT status code.
450 * @retval VERR_BUFFER_OVERFLOW if the output buffer is too small. The buffer
451 * may contain an invalid Base64 string.
452 *
453 * @param pvData The data to encode.
454 * @param cbData The number of bytes to encode.
455 * @param pszBuf Where to put the Base64 string.
456 * @param cbBuf The size of the output buffer, including the terminator.
457 * @param pcchActual The actual number of characters returned.
458 */
459RTDECL(int) RTBase64Encode(const void *pvData, size_t cbData, char *pszBuf, size_t cbBuf, size_t *pcchActual)
460{
461 /*
462 * Process whole "trios" of input data.
463 */
464 uint8_t u8A;
465 uint8_t u8B;
466 uint8_t u8C;
467 size_t cbLineFeed = cbBuf - RTBASE64_LINE_LEN;
468 const uint8_t *pbSrc = (const uint8_t *)pvData;
469 char *pchDst = pszBuf;
470 while (cbData >= 3)
471 {
472 if (cbBuf < 4 + 1)
473 return VERR_BUFFER_OVERFLOW;
474
475 /* encode */
476 u8A = pbSrc[0];
477 pchDst[0] = g_szValToChar[u8A >> 2];
478 u8B = pbSrc[1];
479 pchDst[1] = g_szValToChar[((u8A << 4) & 0x3f) | (u8B >> 4)];
480 u8C = pbSrc[2];
481 pchDst[2] = g_szValToChar[((u8B << 2) & 0x3f) | (u8C >> 6)];
482 pchDst[3] = g_szValToChar[u8C & 0x3f];
483
484 /* advance */
485 cbBuf -= 4;
486 pchDst += 4;
487 cbData -= 3;
488 pbSrc += 3;
489
490 /* deal out linefeeds */
491 if (cbBuf == cbLineFeed && cbData)
492 {
493 if (cbBuf < RTBASE64_EOL_SIZE + 1)
494 return VERR_BUFFER_OVERFLOW;
495 cbBuf -= RTBASE64_EOL_SIZE;
496 if (RTBASE64_EOL_SIZE == 2)
497 *pchDst++ = '\r';
498 *pchDst++ = '\n';
499 cbLineFeed = cbBuf - RTBASE64_LINE_LEN;
500 }
501 }
502
503 /*
504 * Deal with the odd bytes and string termination.
505 */
506 if (cbData)
507 {
508 if (cbBuf < 4 + 1)
509 return VERR_BUFFER_OVERFLOW;
510 switch (cbData)
511 {
512 case 1:
513 u8A = pbSrc[0];
514 pchDst[0] = g_szValToChar[u8A >> 2];
515 pchDst[1] = g_szValToChar[(u8A << 4) & 0x3f];
516 pchDst[2] = '=';
517 pchDst[3] = '=';
518 break;
519 case 2:
520 u8A = pbSrc[0];
521 pchDst[0] = g_szValToChar[u8A >> 2];
522 u8B = pbSrc[1];
523 pchDst[1] = g_szValToChar[((u8A << 4) & 0x3f) | (u8B >> 4)];
524 pchDst[2] = g_szValToChar[(u8B << 2) & 0x3f];
525 pchDst[3] = '=';
526 break;
527 }
528 pchDst += 4;
529 }
530
531 *pchDst = '\0';
532
533 if (pcchActual)
534 *pcchActual = pchDst - pszBuf;
535 return VINF_SUCCESS;
536}
537RT_EXPORT_SYMBOL(RTBase64Encode);
538
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette