base64.c 32.7 KB
Newer Older
1 2 3 4 5 6 7 8 9
/*
 * base64 encoder/decoder
 *
 * Copyright 2005 by Kai Blin
 * Copyright 2006 Juan Lang
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

#include <stdarg.h>
#include "windef.h"
#include "winbase.h"
#include "winerror.h"
#include "wincrypt.h"
#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(crypt);

#define CERT_HEADER          "-----BEGIN CERTIFICATE-----"
32
#define CERT_HEADER_START    "-----BEGIN "
33
#define CERT_DELIMITER       "-----"
34
#define CERT_TRAILER         "-----END CERTIFICATE-----"
35
#define CERT_TRAILER_START   "-----END "
36 37 38 39 40
#define CERT_REQUEST_HEADER  "-----BEGIN NEW CERTIFICATE REQUEST-----"
#define CERT_REQUEST_TRAILER "-----END NEW CERTIFICATE REQUEST-----"
#define X509_HEADER          "-----BEGIN X509 CRL-----"
#define X509_TRAILER         "-----END X509 CRL-----"

41 42 43 44 45 46 47 48 49
static const WCHAR CERT_HEADER_W[] = L"-----BEGIN CERTIFICATE-----";
static const WCHAR CERT_HEADER_START_W[] = L"-----BEGIN ";
static const WCHAR CERT_DELIMITER_W[] = L"-----";
static const WCHAR CERT_TRAILER_W[] = L"-----END CERTIFICATE-----";
static const WCHAR CERT_TRAILER_START_W[] = L"-----END ";
static const WCHAR CERT_REQUEST_HEADER_W[] = L"-----BEGIN NEW CERTIFICATE REQUEST-----";
static const WCHAR CERT_REQUEST_TRAILER_W[] = L"-----END NEW CERTIFICATE REQUEST-----";
static const WCHAR X509_HEADER_W[] = L"-----BEGIN X509 CRL-----";
static const WCHAR X509_TRAILER_W[] = L"-----END X509 CRL-----";
50

51 52 53 54 55
static const char b64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

typedef BOOL (*BinaryToStringAFunc)(const BYTE *pbBinary,
 DWORD cbBinary, DWORD dwFlags, LPSTR pszString, DWORD *pcchString);
56 57
typedef BOOL (*BinaryToStringWFunc)(const BYTE *pbBinary,
 DWORD cbBinary, DWORD dwFlags, LPWSTR pszString, DWORD *pcchString);
58 59 60 61 62 63

static BOOL EncodeBinaryToBinaryA(const BYTE *pbBinary,
 DWORD cbBinary, DWORD dwFlags, LPSTR pszString, DWORD *pcchString)
{
    BOOL ret = TRUE;

64
    if (pszString)
65
    {
66
        if (*pcchString < cbBinary)
67 68 69 70
        {
            SetLastError(ERROR_INSUFFICIENT_BUFFER);
            ret = FALSE;
        }
71
        else if (cbBinary)
72 73
            memcpy(pszString, pbBinary, cbBinary);
    }
74
    else
75
        *pcchString = cbBinary;
76

77 78 79
    return ret;
}

80 81 82 83 84 85 86 87 88
static DWORD stradd(LPSTR ptr, LPCSTR end, LPCSTR s, DWORD slen)
{
    if (ptr + slen > end)
        slen = end - ptr;
    memcpy(ptr, s, slen);
    return slen;
}

static DWORD encodeBase64A(const BYTE *in_buf, int in_len, LPCSTR sep,
89 90 91 92 93 94
 char* out_buf, DWORD *out_len)
{
    int div, i;
    const BYTE *d = in_buf;
    int bytes = (in_len*8 + 5)/6, pad_bytes = (bytes % 4) ? 4 - (bytes % 4) : 0;
    LPSTR ptr;
95 96
    LPCSTR end;
    char chunk[4];
97

98
    if (!out_buf)
99
    {
100 101 102 103
        TRACE("bytes is %d, pad bytes is %d\n", bytes, pad_bytes);
        *out_len = bytes + pad_bytes;
        *out_len += (*out_len / 64 + (*out_len % 64 ? 1 : 0)) * strlen(sep) + 1;
        return 0;
104 105 106 107 108 109
    }

    /* Three bytes of input give 4 chars of output */
    div = in_len / 3;

    ptr = out_buf;
110
    end = ptr + *out_len;
111
    i = 0;
112
    while (div > 0 && ptr < end)
113
    {
114
        if (i && i % 64 == 0)
115
            ptr += stradd(ptr, end, sep, strlen(sep));
116
        /* first char is the first 6 bits of the first byte*/
117
        chunk[0] = b64[ ( d[0] >> 2) & 0x3f ];
118 119
        /* second char is the last 2 bits of the first byte and the first 4
         * bits of the second byte */
120
        chunk[1] = b64[ ((d[0] << 4) & 0x30) | (d[1] >> 4 & 0x0f)];
121 122
        /* third char is the last 4 bits of the second byte and the first 2
         * bits of the third byte */
123
        chunk[2] = b64[ ((d[1] << 2) & 0x3c) | (d[2] >> 6 & 0x03)];
124
        /* fourth char is the remaining 6 bits of the third byte */
125 126
        chunk[3] = b64[   d[2]       & 0x3f];
        ptr += stradd(ptr, end, chunk, 4);
127 128 129 130 131 132 133 134 135
        i += 4;
        d += 3;
        div--;
    }

    switch(pad_bytes)
    {
        case 1:
            /* first char is the first 6 bits of the first byte*/
136
            chunk[0] = b64[ ( d[0] >> 2) & 0x3f ];
137 138
            /* second char is the last 2 bits of the first byte and the first 4
             * bits of the second byte */
139
            chunk[1] = b64[ ((d[0] << 4) & 0x30) | (d[1] >> 4 & 0x0f)];
140 141
            /* third char is the last 4 bits of the second byte padded with
             * two zeroes */
142
            chunk[2] = b64[ ((d[1] << 2) & 0x3c) ];
143
            /* fourth char is a = to indicate one byte of padding */
144 145
            chunk[3] = '=';
            ptr += stradd(ptr, end, chunk, 4);
146 147 148
            break;
        case 2:
            /* first char is the first 6 bits of the first byte*/
149
            chunk[0] = b64[ ( d[0] >> 2) & 0x3f ];
150 151
            /* second char is the last 2 bits of the first byte padded with
             * four zeroes*/
152
            chunk[1] = b64[ ((d[0] << 4) & 0x30)];
153
            /* third char is = to indicate padding */
154
            chunk[2] = '=';
155
            /* fourth char is = to indicate padding */
156 157
            chunk[3] = '=';
            ptr += stradd(ptr, end, chunk, 4);
158 159
            break;
    }
160
    ptr += stradd(ptr, end, sep, strlen(sep));
161

162
    return ptr - out_buf;
163 164 165 166 167 168 169
}

static BOOL BinaryToBase64A(const BYTE *pbBinary,
 DWORD cbBinary, DWORD dwFlags, LPSTR pszString, DWORD *pcchString)
{
    static const char crlf[] = "\r\n", lf[] = "\n";
    BOOL ret = TRUE;
170
    LPCSTR header = NULL, trailer = NULL, sep;
171 172 173 174
    DWORD charsNeeded;

    if (dwFlags & CRYPT_STRING_NOCR)
        sep = lf;
175
    else if (dwFlags & CRYPT_STRING_NOCRLF)
176
        sep = "";
177 178
    else
        sep = crlf;
179
    switch (dwFlags & 0x0fffffff)
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    {
    case CRYPT_STRING_BASE64:
        /* no header or footer */
        break;
    case CRYPT_STRING_BASE64HEADER:
        header = CERT_HEADER;
        trailer = CERT_TRAILER;
        break;
    case CRYPT_STRING_BASE64REQUESTHEADER:
        header = CERT_REQUEST_HEADER;
        trailer = CERT_REQUEST_TRAILER;
        break;
    case CRYPT_STRING_BASE64X509CRLHEADER:
        header = X509_HEADER;
        trailer = X509_TRAILER;
        break;
    }

    charsNeeded = 0;
    encodeBase64A(pbBinary, cbBinary, sep, NULL, &charsNeeded);
    if (header)
        charsNeeded += strlen(header) + strlen(sep);
    if (trailer)
        charsNeeded += strlen(trailer) + strlen(sep);

205 206
    if (pszString)
    {
207 208 209 210 211 212 213 214 215 216 217 218
        LPSTR ptr = pszString;
        DWORD size = *pcchString;
        LPSTR end = ptr + size;

        if (header)
        {
            ptr += stradd(ptr, end, header, strlen(header));
            ptr += stradd(ptr, end, sep, strlen(sep));
            size = end - ptr;
        }
        ptr += encodeBase64A(pbBinary, cbBinary, sep, ptr, &size);
        if (trailer)
219
        {
220 221 222
            ptr += stradd(ptr, end, trailer, strlen(trailer));
            ptr += stradd(ptr, end, sep, strlen(sep));
        }
223

224 225 226 227 228
        if (ptr < end)
            *ptr = '\0';

        if (charsNeeded <= *pcchString)
        {
229
            *pcchString = charsNeeded - 1;
230
        }
231
        else
232
        {
233
            *pcchString = charsNeeded;
234
            SetLastError(ERROR_MORE_DATA);
235
            ret = FALSE;
236 237 238 239
        }
    }
    else
        *pcchString = charsNeeded;
240

241 242 243 244 245 246 247 248
    return ret;
}

BOOL WINAPI CryptBinaryToStringA(const BYTE *pbBinary,
 DWORD cbBinary, DWORD dwFlags, LPSTR pszString, DWORD *pcchString)
{
    BinaryToStringAFunc encoder = NULL;

249
    TRACE("(%p, %d, %08x, %p, %p)\n", pbBinary, cbBinary, dwFlags, pszString,
250 251 252 253 254 255 256 257 258 259 260 261 262
     pcchString);

    if (!pbBinary)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
    if (!pcchString)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

263
    switch (dwFlags & 0x0fffffff)
264 265 266 267 268 269 270 271 272 273 274 275 276 277
    {
    case CRYPT_STRING_BINARY:
        encoder = EncodeBinaryToBinaryA;
        break;
    case CRYPT_STRING_BASE64:
    case CRYPT_STRING_BASE64HEADER:
    case CRYPT_STRING_BASE64REQUESTHEADER:
    case CRYPT_STRING_BASE64X509CRLHEADER:
        encoder = BinaryToBase64A;
        break;
    case CRYPT_STRING_HEX:
    case CRYPT_STRING_HEXASCII:
    case CRYPT_STRING_HEXADDR:
    case CRYPT_STRING_HEXASCIIADDR:
278
        FIXME("Unimplemented type %d\n", dwFlags & 0x0fffffff);
279 280 281 282 283 284 285 286
        /* fall through */
    default:
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
    return encoder(pbBinary, cbBinary, dwFlags, pszString, pcchString);
}

287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
static BOOL EncodeBinaryToBinaryW(const BYTE *in_buf, DWORD in_len, DWORD flags, WCHAR *out_buf, DWORD *out_len)
{
    BOOL ret = TRUE;

    if (out_buf)
    {
        if (*out_len < in_len)
        {
            SetLastError(ERROR_INSUFFICIENT_BUFFER);
            ret = FALSE;
        }
        else if (in_len)
            memcpy(out_buf, in_buf, in_len);
    }
    else
        *out_len = in_len;

    return ret;
}

307 308 309 310 311 312 313 314 315 316
static LONG encodeBase64W(const BYTE *in_buf, int in_len, LPCWSTR sep,
 WCHAR* out_buf, DWORD *out_len)
{
    int div, i;
    const BYTE *d = in_buf;
    int bytes = (in_len*8 + 5)/6, pad_bytes = (bytes % 4) ? 4 - (bytes % 4) : 0;
    DWORD needed;
    LPWSTR ptr;

    TRACE("bytes is %d, pad bytes is %d\n", bytes, pad_bytes);
317
    needed = bytes + pad_bytes;
318
    needed += (needed / 64 + (needed % 64 ? 1 : 0)) * lstrlenW(sep);
319
    needed++;
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335

    if (needed > *out_len)
    {
        *out_len = needed;
        return ERROR_INSUFFICIENT_BUFFER;
    }
    else
        *out_len = needed;

    /* Three bytes of input give 4 chars of output */
    div = in_len / 3;

    ptr = out_buf;
    i = 0;
    while (div > 0)
    {
336
        if (i && i % 64 == 0)
337
        {
338 339
            lstrcpyW(ptr, sep);
            ptr += lstrlenW(sep);
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
        }
        /* first char is the first 6 bits of the first byte*/
        *ptr++ = b64[ ( d[0] >> 2) & 0x3f ];
        /* second char is the last 2 bits of the first byte and the first 4
         * bits of the second byte */
        *ptr++ = b64[ ((d[0] << 4) & 0x30) | (d[1] >> 4 & 0x0f)];
        /* third char is the last 4 bits of the second byte and the first 2
         * bits of the third byte */
        *ptr++ = b64[ ((d[1] << 2) & 0x3c) | (d[2] >> 6 & 0x03)];
        /* fourth char is the remaining 6 bits of the third byte */
        *ptr++ = b64[   d[2]       & 0x3f];
        i += 4;
        d += 3;
        div--;
    }

    switch(pad_bytes)
    {
        case 1:
            /* first char is the first 6 bits of the first byte*/
            *ptr++ = b64[ ( d[0] >> 2) & 0x3f ];
            /* second char is the last 2 bits of the first byte and the first 4
             * bits of the second byte */
            *ptr++ = b64[ ((d[0] << 4) & 0x30) | (d[1] >> 4 & 0x0f)];
            /* third char is the last 4 bits of the second byte padded with
             * two zeroes */
            *ptr++ = b64[ ((d[1] << 2) & 0x3c) ];
            /* fourth char is a = to indicate one byte of padding */
            *ptr++ = '=';
            break;
        case 2:
            /* first char is the first 6 bits of the first byte*/
            *ptr++ = b64[ ( d[0] >> 2) & 0x3f ];
            /* second char is the last 2 bits of the first byte padded with
             * four zeroes*/
            *ptr++ = b64[ ((d[0] << 4) & 0x30)];
            /* third char is = to indicate padding */
            *ptr++ = '=';
            /* fourth char is = to indicate padding */
            *ptr++ = '=';
            break;
    }
382
    lstrcpyW(ptr, sep);
383 384 385 386 387 388 389 390

    return ERROR_SUCCESS;
}

static BOOL BinaryToBase64W(const BYTE *pbBinary,
 DWORD cbBinary, DWORD dwFlags, LPWSTR pszString, DWORD *pcchString)
{
    BOOL ret = TRUE;
391
    LPCWSTR header = NULL, trailer = NULL, sep;
392 393 394
    DWORD charsNeeded;

    if (dwFlags & CRYPT_STRING_NOCR)
395
        sep = L"\n";
396
    else if (dwFlags & CRYPT_STRING_NOCRLF)
397
        sep = L"";
398
    else
399
        sep = L"\r\n";
400
    switch (dwFlags & 0x0fffffff)
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
    {
    case CRYPT_STRING_BASE64:
        /* no header or footer */
        break;
    case CRYPT_STRING_BASE64HEADER:
        header = CERT_HEADER_W;
        trailer = CERT_TRAILER_W;
        break;
    case CRYPT_STRING_BASE64REQUESTHEADER:
        header = CERT_REQUEST_HEADER_W;
        trailer = CERT_REQUEST_TRAILER_W;
        break;
    case CRYPT_STRING_BASE64X509CRLHEADER:
        header = X509_HEADER_W;
        trailer = X509_TRAILER_W;
        break;
    }

    charsNeeded = 0;
    encodeBase64W(pbBinary, cbBinary, sep, NULL, &charsNeeded);
    if (header)
422
        charsNeeded += lstrlenW(header) + lstrlenW(sep);
423
    if (trailer)
424
        charsNeeded += lstrlenW(trailer) + lstrlenW(sep);
425

426 427 428
    if (pszString)
    {
        if (charsNeeded <= *pcchString)
429
        {
430 431 432 433 434
            LPWSTR ptr = pszString;
            DWORD size = charsNeeded;

            if (header)
            {
435 436 437 438
                lstrcpyW(ptr, header);
                ptr += lstrlenW(ptr);
                lstrcpyW(ptr, sep);
                ptr += lstrlenW(sep);
439 440 441 442 443
            }
            encodeBase64W(pbBinary, cbBinary, sep, ptr, &size);
            ptr += size - 1;
            if (trailer)
            {
444 445 446
                lstrcpyW(ptr, trailer);
                ptr += lstrlenW(ptr);
                lstrcpyW(ptr, sep);
447 448
            }
            *pcchString = charsNeeded - 1;
449
        }
450
        else
451
        {
452
            *pcchString = charsNeeded;
453
            SetLastError(ERROR_MORE_DATA);
454
            ret = FALSE;
455 456 457 458
        }
    }
    else
        *pcchString = charsNeeded;
459

460 461 462
    return ret;
}

463
static BOOL BinaryToHexRawW(const BYTE *bin, DWORD nbin, DWORD flags, LPWSTR str, DWORD *nstr)
464
{
465
    static const WCHAR hex[] = L"0123456789abcdef";
466 467 468 469 470 471 472 473 474 475
    DWORD needed;

    if (flags & CRYPT_STRING_NOCRLF)
        needed = 0;
    else if (flags & CRYPT_STRING_NOCR)
        needed = 1;
    else
        needed = 2;

    needed += nbin * 2 + 1;
476 477 478 479 480 481 482

    if (!str)
    {
        *nstr = needed;
        return TRUE;
    }

483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
    if (needed > *nstr)
    {
        SetLastError(ERROR_MORE_DATA);
        return FALSE;
    }

    while (nbin--)
    {
        *str++ = hex[(*bin >> 4) & 0xf];
        *str++ = hex[*bin & 0xf];
        bin++;
    }

    if (flags & CRYPT_STRING_NOCR)
        *str++ = '\n';
    else if (!(flags & CRYPT_STRING_NOCRLF))
    {
        *str++ = '\r';
        *str++ = '\n';
    }

    *str = 0;
    *nstr = needed - 1;
    return TRUE;
}

509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
static BOOL binary_to_hexW(const BYTE *bin, DWORD nbin, DWORD flags, LPWSTR str, DWORD *nstr)
{
    static const WCHAR hex[] = L"0123456789abcdef";
    DWORD needed, i;

    needed = nbin * 3; /* spaces + terminating \0 */

    if (flags & CRYPT_STRING_NOCR)
    {
        needed += (nbin + 7) / 16; /* space every 16 characters */
        needed += 1; /* terminating \n */
    }
    else if (!(flags & CRYPT_STRING_NOCRLF))
    {
        needed += (nbin + 7) / 16; /* space every 16 characters */
        needed += nbin / 16 + 1; /* LF every 16 characters + terminating \r */

        if (nbin % 16)
            needed += 1; /* terminating \n */
    }

    if (!str)
    {
        *nstr = needed;
        return TRUE;
    }

    if (needed > *nstr)
    {
        SetLastError(ERROR_MORE_DATA);
        return FALSE;
    }

    for (i = 0; i < nbin; i++)
    {
        *str++ = hex[(bin[i] >> 4) & 0xf];
        *str++ = hex[bin[i] & 0xf];

        if (i >= nbin - 1) break;

        if (i && !(flags & CRYPT_STRING_NOCRLF))
        {
            if (!((i + 1) % 16))
            {
                if (flags & CRYPT_STRING_NOCR)
                    *str++ = '\n';
                else
                {
                    *str++ = '\r';
                    *str++ = '\n';
                }
                continue;
            }
            else if (!((i + 1) % 8))
                *str++ = ' ';
        }

        *str++ = ' ';
    }

    if (flags & CRYPT_STRING_NOCR)
        *str++ = '\n';
    else if (!(flags & CRYPT_STRING_NOCRLF))
    {
        *str++ = '\r';
        *str++ = '\n';
    }

    *str = 0;
    *nstr = needed - 1;
    return TRUE;
}

582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
BOOL WINAPI CryptBinaryToStringW(const BYTE *pbBinary,
 DWORD cbBinary, DWORD dwFlags, LPWSTR pszString, DWORD *pcchString)
{
    BinaryToStringWFunc encoder = NULL;

    TRACE("(%p, %d, %08x, %p, %p)\n", pbBinary, cbBinary, dwFlags, pszString,
     pcchString);

    if (!pbBinary)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
    if (!pcchString)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

601
    switch (dwFlags & 0x0fffffff)
602
    {
603 604 605
    case CRYPT_STRING_BINARY:
        encoder = EncodeBinaryToBinaryW;
        break;
606 607 608 609 610 611
    case CRYPT_STRING_BASE64:
    case CRYPT_STRING_BASE64HEADER:
    case CRYPT_STRING_BASE64REQUESTHEADER:
    case CRYPT_STRING_BASE64X509CRLHEADER:
        encoder = BinaryToBase64W;
        break;
612
    case CRYPT_STRING_HEXRAW:
613
        encoder = BinaryToHexRawW;
614
        break;
615
    case CRYPT_STRING_HEX:
616 617
        encoder = binary_to_hexW;
        break;
618 619 620
    case CRYPT_STRING_HEXASCII:
    case CRYPT_STRING_HEXADDR:
    case CRYPT_STRING_HEXASCIIADDR:
621
        FIXME("Unimplemented type %d\n", dwFlags & 0x0fffffff);
622 623 624 625 626 627 628 629
        /* fall through */
    default:
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
    return encoder(pbBinary, cbBinary, dwFlags, pszString, pcchString);
}

630 631 632 633 634
#define BASE64_DECODE_PADDING    0x100
#define BASE64_DECODE_WHITESPACE 0x200
#define BASE64_DECODE_INVALID    0x300

static inline int decodeBase64Byte(int c)
635
{
636
    int ret = BASE64_DECODE_INVALID;
637 638 639 640 641 642 643 644 645 646 647

    if (c >= 'A' && c <= 'Z')
        ret = c - 'A';
    else if (c >= 'a' && c <= 'z')
        ret = c - 'a' + 26;
    else if (c >= '0' && c <= '9')
        ret = c - '0' + 52;
    else if (c == '+')
        ret = 62;
    else if (c == '/')
        ret = 63;
648 649 650 651
    else if (c == '=')
        ret = BASE64_DECODE_PADDING;
    else if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
        ret = BASE64_DECODE_WHITESPACE;
652 653 654
    return ret;
}

655 656 657 658 659
/* Unlike CryptStringToBinaryA, cchString is guaranteed to be the length of the
 * string to convert.
 */
typedef LONG (*StringToBinaryAFunc)(LPCSTR pszString, DWORD cchString,
 BYTE *pbBinary, DWORD *pcbBinary, DWORD *pdwSkip, DWORD *pdwFlags);
660

661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
static LONG Base64ToBinary(const void* pszString, BOOL wide, DWORD cchString,
 BYTE *pbBinary, DWORD *pcbBinary, DWORD *pdwSkip, DWORD *pdwFlags)
{
    DWORD cbIn, cbValid, cbOut, hasPadding;
    BYTE block[4];
    for (cbIn = cbValid = cbOut = hasPadding = 0; cbIn < cchString; ++cbIn)
    {
        int c = wide ? (int)((WCHAR*)pszString)[cbIn] : (int)((char*)pszString)[cbIn];
        int d = decodeBase64Byte(c);
        if (d == BASE64_DECODE_INVALID)
            goto invalid;
        if (d == BASE64_DECODE_WHITESPACE)
            continue;

        /* When padding starts, data is not acceptable */
        if (hasPadding && d != BASE64_DECODE_PADDING)
            goto invalid;

        /* Padding after a full block (like "VVVV=") is ok and stops decoding */
        if (d == BASE64_DECODE_PADDING && (cbValid & 3) == 0)
            break;
682

683
        cbValid += 1;
684

685
        if (d == BASE64_DECODE_PADDING)
686
        {
687 688 689 690 691
            hasPadding = 1;
            /* When padding reaches a full block, stop decoding */
            if ((cbValid & 3) == 0)
                break;
            continue;
692 693
        }

694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
        /* cbOut is incremented in the 4-char block as follows: "1-23" */
        if ((cbValid & 3) != 2)
            cbOut += 1;
    }
    /* Fail if the block has bad padding; omitting padding is fine */
    if ((cbValid & 3) != 0 && hasPadding)
        goto invalid;
    /* Check available buffer size */
    if (pbBinary && *pcbBinary && cbOut > *pcbBinary)
        goto overflow;
    /* Convert the data; this step depends on the validity checks above! */
    if (pbBinary) for (cbIn = cbValid = cbOut = 0; cbIn < cchString; ++cbIn)
    {
        int c = wide ? (int)((WCHAR*)pszString)[cbIn] : (int)((char*)pszString)[cbIn];
        int d = decodeBase64Byte(c);
        if (d == BASE64_DECODE_WHITESPACE)
            continue;
        if (d == BASE64_DECODE_PADDING)
            break;
        block[cbValid & 3] = d;
        cbValid += 1;
        switch (cbValid & 3) {
        case 1:
            pbBinary[cbOut++] = (block[0] << 2);
            break;
        case 2:
            pbBinary[cbOut-1] = (block[0] << 2) | (block[1] >> 4);
            break;
        case 3:
            pbBinary[cbOut++] = (block[1] << 4) | (block[2] >> 2);
            break;
        case 0:
            pbBinary[cbOut++] = (block[2] << 6) | (block[3] >> 0);
            break;
728
        }
729 730 731 732 733 734
    }
    *pcbBinary = cbOut;
    if (pdwSkip)
        *pdwSkip = 0;
    if (pdwFlags)
        *pdwFlags = CRYPT_STRING_BASE64;
735
    return ERROR_SUCCESS;
736 737 738 739 740
overflow:
    return ERROR_INSUFFICIENT_BUFFER;
invalid:
    *pcbBinary = cbOut;
    return ERROR_INVALID_DATA;
741 742 743 744 745
}

static LONG Base64ToBinaryA(LPCSTR pszString, DWORD cchString,
 BYTE *pbBinary, DWORD *pcbBinary, DWORD *pdwSkip, DWORD *pdwFlags)
{
746
    return Base64ToBinary(pszString, FALSE, cchString, pbBinary, pcbBinary, pdwSkip, pdwFlags);
747 748 749
}

static LONG Base64WithHeaderAndTrailerToBinaryA(LPCSTR pszString,
750
 DWORD cchString, BYTE *pbBinary,
751
 DWORD *pcbBinary, DWORD *pdwSkip)
752 753
{
    LONG ret;
754 755
    LPCSTR header = CERT_HEADER_START;
    LPCSTR trailer = CERT_TRAILER_START;
756

757 758 759 760 761 762
    LPCSTR headerBegins;
    LPCSTR dataBegins;
    LPCSTR trailerBegins;
    size_t dataLength;

    if ((strlen(header) + strlen(trailer)) > cchString)
763
    {
764 765 766 767 768
        return ERROR_INVALID_DATA;
    }

    if (!(headerBegins = strstr(pszString, header)))
    {
769
        TRACE("Can't find %s in %s.\n", header, debugstr_an(pszString, cchString));
770 771
        return ERROR_INVALID_DATA;
    }
772

773
    dataBegins = headerBegins + strlen(header);
774
    if (!(dataBegins = strstr(dataBegins, CERT_DELIMITER)))
775
    {
776
        return ERROR_INVALID_DATA;
777
    }
778
    dataBegins += strlen(CERT_DELIMITER);
779 780 781
    if (*dataBegins == '\r') dataBegins++;
    if (*dataBegins == '\n') dataBegins++;

782
    if (!(trailerBegins = strstr(dataBegins, trailer)))
783
    {
784
        return ERROR_INVALID_DATA;
785
    }
786 787
    if (*(trailerBegins-1) == '\n') trailerBegins--;
    if (*(trailerBegins-1) == '\r') trailerBegins--;
788 789 790 791 792 793 794 795 796

    if (pdwSkip)
       *pdwSkip = headerBegins - pszString;

    dataLength = trailerBegins - dataBegins;

    ret = Base64ToBinaryA(dataBegins, dataLength, pbBinary, pcbBinary, NULL,
          NULL);

797 798 799 800 801 802 803
    return ret;
}

static LONG Base64HeaderToBinaryA(LPCSTR pszString, DWORD cchString,
 BYTE *pbBinary, DWORD *pcbBinary, DWORD *pdwSkip, DWORD *pdwFlags)
{
    LONG ret = Base64WithHeaderAndTrailerToBinaryA(pszString, cchString,
804
     pbBinary, pcbBinary, pdwSkip);
805 806 807 808 809 810 811 812 813 814

    if (!ret && pdwFlags)
        *pdwFlags = CRYPT_STRING_BASE64HEADER;
    return ret;
}

static LONG Base64RequestHeaderToBinaryA(LPCSTR pszString, DWORD cchString,
 BYTE *pbBinary, DWORD *pcbBinary, DWORD *pdwSkip, DWORD *pdwFlags)
{
    LONG ret = Base64WithHeaderAndTrailerToBinaryA(pszString, cchString,
815
     pbBinary, pcbBinary, pdwSkip);
816 817 818 819 820 821 822 823 824 825

    if (!ret && pdwFlags)
        *pdwFlags = CRYPT_STRING_BASE64REQUESTHEADER;
    return ret;
}

static LONG Base64X509HeaderToBinaryA(LPCSTR pszString, DWORD cchString,
 BYTE *pbBinary, DWORD *pcbBinary, DWORD *pdwSkip, DWORD *pdwFlags)
{
    LONG ret = Base64WithHeaderAndTrailerToBinaryA(pszString, cchString,
826
     pbBinary, pcbBinary, pdwSkip);
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892

    if (!ret && pdwFlags)
        *pdwFlags = CRYPT_STRING_BASE64X509CRLHEADER;
    return ret;
}

static LONG Base64AnyToBinaryA(LPCSTR pszString, DWORD cchString,
 BYTE *pbBinary, DWORD *pcbBinary, DWORD *pdwSkip, DWORD *pdwFlags)
{
    LONG ret;

    ret = Base64HeaderToBinaryA(pszString, cchString, pbBinary, pcbBinary,
     pdwSkip, pdwFlags);
    if (ret == ERROR_INVALID_DATA)
        ret = Base64ToBinaryA(pszString, cchString, pbBinary, pcbBinary,
         pdwSkip, pdwFlags);
    return ret;
}

static LONG DecodeBinaryToBinaryA(LPCSTR pszString, DWORD cchString,
 BYTE *pbBinary, DWORD *pcbBinary, DWORD *pdwSkip, DWORD *pdwFlags)
{
    LONG ret = ERROR_SUCCESS;

    if (*pcbBinary < cchString)
    {
        if (!pbBinary)
            *pcbBinary = cchString;
        else
        {
            ret = ERROR_INSUFFICIENT_BUFFER;
            *pcbBinary = cchString;
        }
    }
    else
    {
        if (cchString)
            memcpy(pbBinary, pszString, cchString);
        *pcbBinary = cchString;
    }
    return ret;
}

static LONG DecodeAnyA(LPCSTR pszString, DWORD cchString,
 BYTE *pbBinary, DWORD *pcbBinary, DWORD *pdwSkip, DWORD *pdwFlags)
{
    LONG ret;

    ret = Base64HeaderToBinaryA(pszString, cchString, pbBinary, pcbBinary,
     pdwSkip, pdwFlags);
    if (ret == ERROR_INVALID_DATA)
        ret = Base64ToBinaryA(pszString, cchString, pbBinary, pcbBinary,
         pdwSkip, pdwFlags);
    if (ret == ERROR_INVALID_DATA)
        ret = DecodeBinaryToBinaryA(pszString, cchString, pbBinary, pcbBinary,
         pdwSkip, pdwFlags);
    return ret;
}

BOOL WINAPI CryptStringToBinaryA(LPCSTR pszString,
 DWORD cchString, DWORD dwFlags, BYTE *pbBinary, DWORD *pcbBinary,
 DWORD *pdwSkip, DWORD *pdwFlags)
{
    StringToBinaryAFunc decoder;
    LONG ret;

893
    TRACE("(%s, %d, %08x, %p, %p, %p, %p)\n", debugstr_an(pszString, cchString ? cchString : -1),
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
     cchString, dwFlags, pbBinary, pcbBinary, pdwSkip, pdwFlags);

    if (!pszString)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
    /* Only the bottom byte contains valid types */
    if (dwFlags & 0xfffffff0)
    {
        SetLastError(ERROR_INVALID_DATA);
        return FALSE;
    }
    switch (dwFlags)
    {
    case CRYPT_STRING_BASE64_ANY:
        decoder = Base64AnyToBinaryA;
        break;
    case CRYPT_STRING_BASE64:
        decoder = Base64ToBinaryA;
        break;
    case CRYPT_STRING_BASE64HEADER:
        decoder = Base64HeaderToBinaryA;
        break;
    case CRYPT_STRING_BASE64REQUESTHEADER:
        decoder = Base64RequestHeaderToBinaryA;
        break;
    case CRYPT_STRING_BASE64X509CRLHEADER:
        decoder = Base64X509HeaderToBinaryA;
        break;
    case CRYPT_STRING_BINARY:
        decoder = DecodeBinaryToBinaryA;
        break;
    case CRYPT_STRING_ANY:
        decoder = DecodeAnyA;
        break;
    case CRYPT_STRING_HEX:
    case CRYPT_STRING_HEXASCII:
    case CRYPT_STRING_HEXADDR:
    case CRYPT_STRING_HEXASCIIADDR:
934
        FIXME("Unimplemented type %d\n", dwFlags & 0x7fffffff);
935 936 937 938 939 940 941 942 943 944
        /* fall through */
    default:
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
    if (!cchString)
        cchString = strlen(pszString);
    ret = decoder(pszString, cchString, pbBinary, pcbBinary, pdwSkip, pdwFlags);
    if (ret)
        SetLastError(ret);
945
    return ret == ERROR_SUCCESS;
946
}
947 948 949 950 951 952 953 954 955 956

/* Unlike CryptStringToBinaryW, cchString is guaranteed to be the length of the
 * string to convert.
 */
typedef LONG (*StringToBinaryWFunc)(LPCWSTR pszString, DWORD cchString,
 BYTE *pbBinary, DWORD *pcbBinary, DWORD *pdwSkip, DWORD *pdwFlags);

static LONG Base64ToBinaryW(LPCWSTR pszString, DWORD cchString,
 BYTE *pbBinary, DWORD *pcbBinary, DWORD *pdwSkip, DWORD *pdwFlags)
{
957
    return Base64ToBinary(pszString, TRUE, cchString, pbBinary, pcbBinary, pdwSkip, pdwFlags);
958 959 960
}

static LONG Base64WithHeaderAndTrailerToBinaryW(LPCWSTR pszString,
961
 DWORD cchString, BYTE *pbBinary,
962
 DWORD *pcbBinary, DWORD *pdwSkip)
963 964
{
    LONG ret;
965 966
    LPCWSTR header = CERT_HEADER_START_W;
    LPCWSTR trailer = CERT_TRAILER_START_W;
967

968 969 970 971 972
    LPCWSTR headerBegins;
    LPCWSTR dataBegins;
    LPCWSTR trailerBegins;
    size_t dataLength;

973
    if ((lstrlenW(header) + lstrlenW(trailer)) > cchString)
974
    {
975 976 977
        return ERROR_INVALID_DATA;
    }

978
    if (!(headerBegins = wcsstr(pszString, header)))
979
    {
980
        TRACE("Can't find %s in %s.\n", debugstr_w(header), debugstr_wn(pszString, cchString));
981 982
        return ERROR_INVALID_DATA;
    }
983

984 985
    dataBegins = headerBegins + lstrlenW(header);
    if (!(dataBegins = wcsstr(dataBegins, CERT_DELIMITER_W)))
986
    {
987
        return ERROR_INVALID_DATA;
988
    }
989
    dataBegins += lstrlenW(CERT_DELIMITER_W);
990 991 992
    if (*dataBegins == '\r') dataBegins++;
    if (*dataBegins == '\n') dataBegins++;

993
    if (!(trailerBegins = wcsstr(dataBegins, trailer)))
994
    {
995
        return ERROR_INVALID_DATA;
996
    }
997 998
    if (*(trailerBegins-1) == '\n') trailerBegins--;
    if (*(trailerBegins-1) == '\r') trailerBegins--;
999 1000 1001 1002 1003 1004 1005 1006 1007

    if (pdwSkip)
       *pdwSkip = headerBegins - pszString;

    dataLength = trailerBegins - dataBegins;

    ret = Base64ToBinaryW(dataBegins, dataLength, pbBinary, pcbBinary, NULL,
          NULL);

1008 1009 1010 1011 1012 1013 1014
    return ret;
}

static LONG Base64HeaderToBinaryW(LPCWSTR pszString, DWORD cchString,
 BYTE *pbBinary, DWORD *pcbBinary, DWORD *pdwSkip, DWORD *pdwFlags)
{
    LONG ret = Base64WithHeaderAndTrailerToBinaryW(pszString, cchString,
1015
     pbBinary, pcbBinary, pdwSkip);
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025

    if (!ret && pdwFlags)
        *pdwFlags = CRYPT_STRING_BASE64HEADER;
    return ret;
}

static LONG Base64RequestHeaderToBinaryW(LPCWSTR pszString, DWORD cchString,
 BYTE *pbBinary, DWORD *pcbBinary, DWORD *pdwSkip, DWORD *pdwFlags)
{
    LONG ret = Base64WithHeaderAndTrailerToBinaryW(pszString, cchString,
1026
     pbBinary, pcbBinary, pdwSkip);
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036

    if (!ret && pdwFlags)
        *pdwFlags = CRYPT_STRING_BASE64REQUESTHEADER;
    return ret;
}

static LONG Base64X509HeaderToBinaryW(LPCWSTR pszString, DWORD cchString,
 BYTE *pbBinary, DWORD *pcbBinary, DWORD *pdwSkip, DWORD *pdwFlags)
{
    LONG ret = Base64WithHeaderAndTrailerToBinaryW(pszString, cchString,
1037
     pbBinary, pcbBinary, pdwSkip);
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103

    if (!ret && pdwFlags)
        *pdwFlags = CRYPT_STRING_BASE64X509CRLHEADER;
    return ret;
}

static LONG Base64AnyToBinaryW(LPCWSTR pszString, DWORD cchString,
 BYTE *pbBinary, DWORD *pcbBinary, DWORD *pdwSkip, DWORD *pdwFlags)
{
    LONG ret;

    ret = Base64HeaderToBinaryW(pszString, cchString, pbBinary, pcbBinary,
     pdwSkip, pdwFlags);
    if (ret == ERROR_INVALID_DATA)
        ret = Base64ToBinaryW(pszString, cchString, pbBinary, pcbBinary,
         pdwSkip, pdwFlags);
    return ret;
}

static LONG DecodeBinaryToBinaryW(LPCWSTR pszString, DWORD cchString,
 BYTE *pbBinary, DWORD *pcbBinary, DWORD *pdwSkip, DWORD *pdwFlags)
{
    LONG ret = ERROR_SUCCESS;

    if (*pcbBinary < cchString)
    {
        if (!pbBinary)
            *pcbBinary = cchString;
        else
        {
            ret = ERROR_INSUFFICIENT_BUFFER;
            *pcbBinary = cchString;
        }
    }
    else
    {
        if (cchString)
            memcpy(pbBinary, pszString, cchString * sizeof(WCHAR));
        *pcbBinary = cchString * sizeof(WCHAR);
    }
    return ret;
}

static LONG DecodeAnyW(LPCWSTR pszString, DWORD cchString,
 BYTE *pbBinary, DWORD *pcbBinary, DWORD *pdwSkip, DWORD *pdwFlags)
{
    LONG ret;

    ret = Base64HeaderToBinaryW(pszString, cchString, pbBinary, pcbBinary,
     pdwSkip, pdwFlags);
    if (ret == ERROR_INVALID_DATA)
        ret = Base64ToBinaryW(pszString, cchString, pbBinary, pcbBinary,
         pdwSkip, pdwFlags);
    if (ret == ERROR_INVALID_DATA)
        ret = DecodeBinaryToBinaryW(pszString, cchString, pbBinary, pcbBinary,
         pdwSkip, pdwFlags);
    return ret;
}

BOOL WINAPI CryptStringToBinaryW(LPCWSTR pszString,
 DWORD cchString, DWORD dwFlags, BYTE *pbBinary, DWORD *pcbBinary,
 DWORD *pdwSkip, DWORD *pdwFlags)
{
    StringToBinaryWFunc decoder;
    LONG ret;

1104
    TRACE("(%s, %d, %08x, %p, %p, %p, %p)\n", debugstr_wn(pszString, cchString ? cchString : -1),
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
     cchString, dwFlags, pbBinary, pcbBinary, pdwSkip, pdwFlags);

    if (!pszString)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
    /* Only the bottom byte contains valid types */
    if (dwFlags & 0xfffffff0)
    {
        SetLastError(ERROR_INVALID_DATA);
        return FALSE;
    }
    switch (dwFlags)
    {
    case CRYPT_STRING_BASE64_ANY:
        decoder = Base64AnyToBinaryW;
        break;
    case CRYPT_STRING_BASE64:
        decoder = Base64ToBinaryW;
        break;
    case CRYPT_STRING_BASE64HEADER:
        decoder = Base64HeaderToBinaryW;
        break;
    case CRYPT_STRING_BASE64REQUESTHEADER:
        decoder = Base64RequestHeaderToBinaryW;
        break;
    case CRYPT_STRING_BASE64X509CRLHEADER:
        decoder = Base64X509HeaderToBinaryW;
        break;
    case CRYPT_STRING_BINARY:
        decoder = DecodeBinaryToBinaryW;
        break;
    case CRYPT_STRING_ANY:
        decoder = DecodeAnyW;
        break;
    case CRYPT_STRING_HEX:
    case CRYPT_STRING_HEXASCII:
    case CRYPT_STRING_HEXADDR:
    case CRYPT_STRING_HEXASCIIADDR:
        FIXME("Unimplemented type %d\n", dwFlags & 0x7fffffff);
        /* fall through */
    default:
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
    if (!cchString)
1152
        cchString = lstrlenW(pszString);
1153 1154 1155
    ret = decoder(pszString, cchString, pbBinary, pcbBinary, pdwSkip, pdwFlags);
    if (ret)
        SetLastError(ret);
1156
    return ret == ERROR_SUCCESS;
1157
}