base64.c 33.3 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
 *
 * 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"
28
#include "wine/unicode.h"
29 30 31 32

WINE_DEFAULT_DEBUG_CHANNEL(crypt);

#define CERT_HEADER          "-----BEGIN CERTIFICATE-----"
33 34
#define CERT_HEADER_START    "-----BEGIN"
#define CERT_DELIMITER       "-----"
35
#define CERT_TRAILER         "-----END CERTIFICATE-----"
36
#define CERT_TRAILER_START   "-----END"
37 38 39 40 41
#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-----"

42 43 44
static const WCHAR CERT_HEADER_W[] = {
'-','-','-','-','-','B','E','G','I','N',' ','C','E','R','T','I','F','I','C',
'A','T','E','-','-','-','-','-',0 };
45 46 47 48
static const WCHAR CERT_HEADER_START_W[] = {
'-','-','-','-','-','B','E','G','I','N',0 };
static const WCHAR CERT_DELIMITER_W[] = {
'-','-','-','-','-',0 };
49
static const WCHAR CERT_TRAILER_W[] = {
50 51
'-','-','-','-','-','E','N','D',0 };
static const WCHAR CERT_TRAILER_START_W[] = {
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
'-','-','-','-','-','E','N','D',' ','C','E','R','T','I','F','I','C','A','T',
'E','-','-','-','-','-',0 };
static const WCHAR CERT_REQUEST_HEADER_W[] = {
'-','-','-','-','-','B','E','G','I','N',' ','N','E','W',' ','C','E','R','T',
'I','F','I','C','A','T','E','R','E','Q','U','E','S','T','-','-','-','-','-',0 };
static const WCHAR CERT_REQUEST_TRAILER_W[] = {
'-','-','-','-','-','E','N','D',' ','N','E','W',' ','C','E','R','T','I','F',
'I','C','A','T','E','R','E','Q','U','E','S','T','-','-','-','-','-',0 };
static const WCHAR X509_HEADER_W[] = {
'-','-','-','-','-','B','E','G','I','N',' ','X','5','0','9',' ','C','R','L',
'-','-','-','-','-',0 };
static const WCHAR X509_TRAILER_W[] = {
'-','-','-','-','-','E','N','D',' ','X','5','0','9',' ','C','R','L','-','-',
'-','-','-',0 };

67 68 69 70 71
static const char b64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

typedef BOOL (*BinaryToStringAFunc)(const BYTE *pbBinary,
 DWORD cbBinary, DWORD dwFlags, LPSTR pszString, DWORD *pcchString);
72 73
typedef BOOL (*BinaryToStringWFunc)(const BYTE *pbBinary,
 DWORD cbBinary, DWORD dwFlags, LPWSTR pszString, DWORD *pcchString);
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

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

    if (*pcchString < cbBinary)
    {
        if (!pszString)
            *pcchString = cbBinary;
        else
        {
            SetLastError(ERROR_INSUFFICIENT_BUFFER);
            *pcchString = cbBinary;
            ret = FALSE;
        }
    }
    else
    {
        if (cbBinary)
            memcpy(pszString, pbBinary, cbBinary);
        *pcchString = cbBinary;
    }
    return ret;
}

static LONG encodeBase64A(const BYTE *in_buf, int in_len, LPCSTR sep,
 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;
    DWORD needed;
    LPSTR ptr;

    TRACE("bytes is %d, pad bytes is %d\n", bytes, pad_bytes);
    needed = bytes + pad_bytes + 1;
111
    needed += (needed / 64 + 1) * strlen(sep);
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127

    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)
    {
128
        if (i && i % 64 == 0)
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
        {
            strcpy(ptr, sep);
            ptr += strlen(sep);
        }
        /* 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;
    }
174
    strcpy(ptr, sep);
175 176 177 178 179 180 181 182 183

    return ERROR_SUCCESS;
}

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;
184
    LPCSTR header = NULL, trailer = NULL, sep;
185 186 187 188
    DWORD charsNeeded;

    if (dwFlags & CRYPT_STRING_NOCR)
        sep = lf;
189
    else if (dwFlags & CRYPT_STRING_NOCRLF)
190
        sep = "";
191 192
    else
        sep = crlf;
193
    switch (dwFlags & 0x0fffffff)
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
    {
    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);
    if (charsNeeded <= *pcchString)
    {
        LPSTR ptr = pszString;
        DWORD size = charsNeeded;

        if (header)
        {
            strcpy(ptr, header);
            ptr += strlen(ptr);
227 228
            strcpy(ptr, sep);
            ptr += strlen(sep);
229 230 231 232 233 234 235
        }
        encodeBase64A(pbBinary, cbBinary, sep, ptr, &size);
        ptr += size - 1;
        if (trailer)
        {
            strcpy(ptr, trailer);
            ptr += strlen(ptr);
236
            strcpy(ptr, sep);
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
        }
        *pcchString = charsNeeded - 1;
    }
    else if (pszString)
    {
        *pcchString = charsNeeded;
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        ret = FALSE;
    }
    else
        *pcchString = charsNeeded;
    return ret;
}

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

256
    TRACE("(%p, %d, %08x, %p, %p)\n", pbBinary, cbBinary, dwFlags, pszString,
257 258 259 260 261 262 263 264 265 266 267 268 269
     pcchString);

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

270
    switch (dwFlags & 0x0fffffff)
271 272 273 274 275 276 277 278 279 280 281 282 283 284
    {
    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:
285
        FIXME("Unimplemented type %d\n", dwFlags & 0x0fffffff);
286 287 288 289 290 291 292 293
        /* fall through */
    default:
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
    return encoder(pbBinary, cbBinary, dwFlags, pszString, pcchString);
}

294 295 296 297 298 299 300 301 302 303 304
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);
    needed = bytes + pad_bytes + 1;
305
    needed += (needed / 64 + 1) * strlenW(sep);
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321

    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)
    {
322
        if (i && i % 64 == 0)
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 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
        {
            strcpyW(ptr, sep);
            ptr += strlenW(sep);
        }
        /* 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;
    }
368
    strcpyW(ptr, sep);
369 370 371 372 373 374 375

    return ERROR_SUCCESS;
}

static BOOL BinaryToBase64W(const BYTE *pbBinary,
 DWORD cbBinary, DWORD dwFlags, LPWSTR pszString, DWORD *pcchString)
{
376
    static const WCHAR crlf[] = { '\r','\n',0 }, lf[] = { '\n',0 }, empty[] = {0};
377
    BOOL ret = TRUE;
378
    LPCWSTR header = NULL, trailer = NULL, sep;
379 380 381 382
    DWORD charsNeeded;

    if (dwFlags & CRYPT_STRING_NOCR)
        sep = lf;
383
    else if (dwFlags & CRYPT_STRING_NOCRLF)
384
        sep = empty;
385 386
    else
        sep = crlf;
387
    switch (dwFlags & 0x0fffffff)
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
    {
    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)
        charsNeeded += strlenW(header) + strlenW(sep);
    if (trailer)
        charsNeeded += strlenW(trailer) + strlenW(sep);
    if (charsNeeded <= *pcchString)
    {
        LPWSTR ptr = pszString;
        DWORD size = charsNeeded;

        if (header)
        {
            strcpyW(ptr, header);
            ptr += strlenW(ptr);
421 422
            strcpyW(ptr, sep);
            ptr += strlenW(sep);
423 424 425 426 427 428 429
        }
        encodeBase64W(pbBinary, cbBinary, sep, ptr, &size);
        ptr += size - 1;
        if (trailer)
        {
            strcpyW(ptr, trailer);
            ptr += strlenW(ptr);
430
            strcpyW(ptr, sep);
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
        }
        *pcchString = charsNeeded - 1;
    }
    else if (pszString)
    {
        *pcchString = charsNeeded;
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        ret = FALSE;
    }
    else
        *pcchString = charsNeeded;
    return ret;
}

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;
    }

464
    switch (dwFlags & 0x0fffffff)
465 466 467 468 469 470 471 472 473 474 475 476
    {
    case CRYPT_STRING_BASE64:
    case CRYPT_STRING_BASE64HEADER:
    case CRYPT_STRING_BASE64REQUESTHEADER:
    case CRYPT_STRING_BASE64X509CRLHEADER:
        encoder = BinaryToBase64W;
        break;
    case CRYPT_STRING_BINARY:
    case CRYPT_STRING_HEX:
    case CRYPT_STRING_HEXASCII:
    case CRYPT_STRING_HEXADDR:
    case CRYPT_STRING_HEXASCIIADDR:
477
        FIXME("Unimplemented type %d\n", dwFlags & 0x0fffffff);
478 479 480 481 482 483 484 485
        /* fall through */
    default:
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
    return encoder(pbBinary, cbBinary, dwFlags, pszString, pcchString);
}

486
static inline BYTE decodeBase64Byte(int c)
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
{
    BYTE ret;

    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;
    else
        ret = 64;
    return ret;
}

static LONG decodeBase64Block(const char *in_buf, int in_len,
 const char **nextBlock, PBYTE out_buf, DWORD *out_len)
{
508
    int len = in_len;
509 510 511 512 513 514 515 516 517 518 519 520 521 522
    const char *d = in_buf;
    int  ip0, ip1, ip2, ip3;

    if (len < 4)
        return ERROR_INVALID_DATA;

    if (d[2] == '=')
    {
        if ((ip0 = decodeBase64Byte(d[0])) > 63)
            return ERROR_INVALID_DATA;
        if ((ip1 = decodeBase64Byte(d[1])) > 63)
            return ERROR_INVALID_DATA;

        if (out_buf)
523 524
            out_buf[0] = (ip0 << 2) | (ip1 >> 4);
        *out_len = 1;
525 526 527 528 529 530 531 532 533 534 535 536
    }
    else if (d[3] == '=')
    {
        if ((ip0 = decodeBase64Byte(d[0])) > 63)
            return ERROR_INVALID_DATA;
        if ((ip1 = decodeBase64Byte(d[1])) > 63)
            return ERROR_INVALID_DATA;
        if ((ip2 = decodeBase64Byte(d[2])) > 63)
            return ERROR_INVALID_DATA;

        if (out_buf)
        {
537 538
            out_buf[0] = (ip0 << 2) | (ip1 >> 4);
            out_buf[1] = (ip1 << 4) | (ip2 >> 2);
539
        }
540
        *out_len = 2;
541 542 543 544 545 546 547 548 549 550 551 552 553 554
    }
    else
    {
        if ((ip0 = decodeBase64Byte(d[0])) > 63)
            return ERROR_INVALID_DATA;
        if ((ip1 = decodeBase64Byte(d[1])) > 63)
            return ERROR_INVALID_DATA;
        if ((ip2 = decodeBase64Byte(d[2])) > 63)
            return ERROR_INVALID_DATA;
        if ((ip3 = decodeBase64Byte(d[3])) > 63)
            return ERROR_INVALID_DATA;

        if (out_buf)
        {
555 556 557
            out_buf[0] = (ip0 << 2) | (ip1 >> 4);
            out_buf[1] = (ip1 << 4) | (ip2 >> 2);
            out_buf[2] = (ip2 << 6) |  ip3;
558
        }
559
        *out_len = 3;
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
    }
    if (len >= 6 && d[4] == '\r' && d[5] == '\n')
        *nextBlock = d + 6;
    else if (len >= 5 && d[4] == '\n')
        *nextBlock = d + 5;
    else if (len >= 4 && d[4])
        *nextBlock = d + 4;
    else
        *nextBlock = NULL;
    return ERROR_SUCCESS;
}

/* 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);

static LONG Base64ToBinaryA(LPCSTR pszString, DWORD cchString,
 BYTE *pbBinary, DWORD *pcbBinary, DWORD *pdwSkip, DWORD *pdwFlags)
{
    LONG ret = ERROR_SUCCESS;
    const char *nextBlock;
    DWORD outLen = 0;

    nextBlock = pszString;
    while (nextBlock && !ret)
    {
        DWORD len = 0;

        ret = decodeBase64Block(nextBlock, cchString - (nextBlock - pszString),
         &nextBlock, pbBinary ? pbBinary + outLen : NULL, &len);
        if (!ret)
            outLen += len;
        if (cchString - (nextBlock - pszString) <= 0)
            nextBlock = NULL;
    }
    *pcbBinary = outLen;
    if (!ret)
    {
        if (pdwSkip)
            *pdwSkip = 0;
        if (pdwFlags)
            *pdwFlags = CRYPT_STRING_BASE64;
    }
    else if (ret == ERROR_INSUFFICIENT_BUFFER)
    {
        if (!pbBinary)
            ret = ERROR_SUCCESS;
    }
    return ret;
}

static LONG Base64WithHeaderAndTrailerToBinaryA(LPCSTR pszString,
 DWORD cchString, LPCSTR header, LPCSTR trailer, BYTE *pbBinary,
615
 DWORD *pcbBinary, DWORD *pdwSkip, BOOL exactHeaderAndTrailerMatch)
616 617 618
{
    LONG ret;

619 620 621 622 623 624
    LPCSTR headerBegins;
    LPCSTR dataBegins;
    LPCSTR trailerBegins;
    size_t dataLength;

    if ((strlen(header) + strlen(trailer)) > cchString)
625
    {
626 627 628 629 630 631 632 633
        return ERROR_INVALID_DATA;
    }

    if (!(headerBegins = strstr(pszString, header)))
    {
        TRACE("Can't find %s in %s.\n", header, pszString);
        return ERROR_INVALID_DATA;
    }
634

635 636 637 638
    dataBegins = headerBegins + strlen(header);
    if (!exactHeaderAndTrailerMatch)
    {
        if ((dataBegins = strstr(dataBegins, CERT_DELIMITER)))
639
        {
640
            dataBegins += strlen(CERT_DELIMITER);
641
        }
642
        else
643
        {
644
            return ERROR_INVALID_DATA;
645
        }
646 647 648 649 650 651 652 653 654 655 656 657 658 659
    }
    if (*dataBegins == '\r') dataBegins++;
    if (*dataBegins == '\n') dataBegins++;

    if (exactHeaderAndTrailerMatch)
    {
        trailerBegins = pszString + cchString - strlen(trailer);
        if (pszString[cchString - 1] == '\n') trailerBegins--;
        if (pszString[cchString - 2] == '\r') trailerBegins--;

        if (*(trailerBegins-1) == '\n') trailerBegins--;
        if (*(trailerBegins-1) == '\r') trailerBegins--;

        if (!strncmp(trailerBegins, trailer, strlen(trailer)))
660
        {
661
            return ERROR_INVALID_DATA;
662 663 664
        }
    }
    else
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
    {
        if (!(trailerBegins = strstr(dataBegins, trailer)))
        {
            return ERROR_INVALID_DATA;
        }
        if (*(trailerBegins-1) == '\n') trailerBegins--;
        if (*(trailerBegins-1) == '\r') trailerBegins--;
    }

    if (pdwSkip)
       *pdwSkip = headerBegins - pszString;

    dataLength = trailerBegins - dataBegins;

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

682 683 684 685 686 687 688
    return ret;
}

static LONG Base64HeaderToBinaryA(LPCSTR pszString, DWORD cchString,
 BYTE *pbBinary, DWORD *pcbBinary, DWORD *pdwSkip, DWORD *pdwFlags)
{
    LONG ret = Base64WithHeaderAndTrailerToBinaryA(pszString, cchString,
689
     CERT_HEADER_START, CERT_TRAILER_START, pbBinary, pcbBinary, pdwSkip, FALSE);
690 691 692 693 694 695 696 697 698 699

    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,
700
     CERT_REQUEST_HEADER, CERT_REQUEST_TRAILER, pbBinary, pcbBinary, pdwSkip, TRUE);
701 702 703 704 705 706 707 708 709 710

    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,
711
     X509_HEADER, X509_TRAILER, pbBinary, pcbBinary, pdwSkip, TRUE);
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777

    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;

778
    TRACE("(%s, %d, %08x, %p, %p, %p, %p)\n", debugstr_a(pszString),
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
     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:
819
        FIXME("Unimplemented type %d\n", dwFlags & 0x7fffffff);
820 821 822 823 824 825 826 827 828 829 830 831
        /* 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);
    return (ret == ERROR_SUCCESS) ? TRUE : FALSE;
}
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 893 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 934 935 936 937 938 939 940 941 942 943 944

static LONG decodeBase64BlockW(const WCHAR *in_buf, int in_len,
 const WCHAR **nextBlock, PBYTE out_buf, DWORD *out_len)
{
    int len = in_len, i;
    const WCHAR *d = in_buf;
    int  ip0, ip1, ip2, ip3;

    if (len < 4)
        return ERROR_INVALID_DATA;

    i = 0;
    if (d[2] == '=')
    {
        if ((ip0 = decodeBase64Byte(d[0])) > 63)
            return ERROR_INVALID_DATA;
        if ((ip1 = decodeBase64Byte(d[1])) > 63)
            return ERROR_INVALID_DATA;

        if (out_buf)
            out_buf[i] = (ip0 << 2) | (ip1 >> 4);
        i++;
    }
    else if (d[3] == '=')
    {
        if ((ip0 = decodeBase64Byte(d[0])) > 63)
            return ERROR_INVALID_DATA;
        if ((ip1 = decodeBase64Byte(d[1])) > 63)
            return ERROR_INVALID_DATA;
        if ((ip2 = decodeBase64Byte(d[2])) > 63)
            return ERROR_INVALID_DATA;

        if (out_buf)
        {
            out_buf[i + 0] = (ip0 << 2) | (ip1 >> 4);
            out_buf[i + 1] = (ip1 << 4) | (ip2 >> 2);
        }
        i += 2;
    }
    else
    {
        if ((ip0 = decodeBase64Byte(d[0])) > 63)
            return ERROR_INVALID_DATA;
        if ((ip1 = decodeBase64Byte(d[1])) > 63)
            return ERROR_INVALID_DATA;
        if ((ip2 = decodeBase64Byte(d[2])) > 63)
            return ERROR_INVALID_DATA;
        if ((ip3 = decodeBase64Byte(d[3])) > 63)
            return ERROR_INVALID_DATA;

        if (out_buf)
        {
            out_buf[i + 0] = (ip0 << 2) | (ip1 >> 4);
            out_buf[i + 1] = (ip1 << 4) | (ip2 >> 2);
            out_buf[i + 2] = (ip2 << 6) |  ip3;
        }
        i += 3;
    }
    if (len >= 6 && d[4] == '\r' && d[5] == '\n')
        *nextBlock = d + 6;
    else if (len >= 5 && d[4] == '\n')
        *nextBlock = d + 5;
    else if (len >= 4 && d[4])
        *nextBlock = d + 4;
    else
        *nextBlock = NULL;
    *out_len = i;
    return ERROR_SUCCESS;
}

/* 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)
{
    LONG ret = ERROR_SUCCESS;
    const WCHAR *nextBlock;
    DWORD outLen = 0;

    nextBlock = pszString;
    while (nextBlock && !ret)
    {
        DWORD len = 0;

        ret = decodeBase64BlockW(nextBlock, cchString - (nextBlock - pszString),
         &nextBlock, pbBinary ? pbBinary + outLen : NULL, &len);
        if (!ret)
            outLen += len;
        if (cchString - (nextBlock - pszString) <= 0)
            nextBlock = NULL;
    }
    *pcbBinary = outLen;
    if (!ret)
    {
        if (pdwSkip)
            *pdwSkip = 0;
        if (pdwFlags)
            *pdwFlags = CRYPT_STRING_BASE64;
    }
    else if (ret == ERROR_INSUFFICIENT_BUFFER)
    {
        if (!pbBinary)
            ret = ERROR_SUCCESS;
    }
    return ret;
}

static LONG Base64WithHeaderAndTrailerToBinaryW(LPCWSTR pszString,
 DWORD cchString, LPCWSTR header, LPCWSTR trailer, BYTE *pbBinary,
945
 DWORD *pcbBinary, DWORD *pdwSkip, BOOL exactHeaderAndTrailerMatch)
946 947 948
{
    LONG ret;

949 950 951 952 953 954
    LPCWSTR headerBegins;
    LPCWSTR dataBegins;
    LPCWSTR trailerBegins;
    size_t dataLength;

    if ((strlenW(header) + strlenW(trailer)) > cchString)
955
    {
956 957 958 959 960 961 962 963
        return ERROR_INVALID_DATA;
    }

    if (!(headerBegins = strstrW(pszString, header)))
    {
        TRACE("Can't find %s in %s.\n", debugstr_w(header), debugstr_w(pszString));
        return ERROR_INVALID_DATA;
    }
964

965 966 967 968
    dataBegins = headerBegins + strlenW(header);
    if (!exactHeaderAndTrailerMatch)
    {
        if ((dataBegins = strstrW(dataBegins, CERT_DELIMITER_W)))
969
        {
970
            dataBegins += strlenW(CERT_DELIMITER_W);
971
        }
972
        else
973
        {
974
            return ERROR_INVALID_DATA;
975
        }
976 977 978 979 980 981 982 983 984 985 986 987 988 989
    }
    if (*dataBegins == '\r') dataBegins++;
    if (*dataBegins == '\n') dataBegins++;

    if (exactHeaderAndTrailerMatch)
    {
        trailerBegins = pszString + cchString - strlenW(trailer);
        if (pszString[cchString - 1] == '\n') trailerBegins--;
        if (pszString[cchString - 2] == '\r') trailerBegins--;

        if (*(trailerBegins-1) == '\n') trailerBegins--;
        if (*(trailerBegins-1) == '\r') trailerBegins--;

        if (!strncmpW(trailerBegins, trailer, strlenW(trailer)))
990
        {
991
            return ERROR_INVALID_DATA;
992 993 994
        }
    }
    else
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
    {
        if (!(trailerBegins = strstrW(dataBegins, trailer)))
        {
            return ERROR_INVALID_DATA;
        }
        if (*(trailerBegins-1) == '\n') trailerBegins--;
        if (*(trailerBegins-1) == '\r') trailerBegins--;
    }

    if (pdwSkip)
       *pdwSkip = headerBegins - pszString;

    dataLength = trailerBegins - dataBegins;

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

1012 1013 1014 1015 1016 1017 1018
    return ret;
}

static LONG Base64HeaderToBinaryW(LPCWSTR pszString, DWORD cchString,
 BYTE *pbBinary, DWORD *pcbBinary, DWORD *pdwSkip, DWORD *pdwFlags)
{
    LONG ret = Base64WithHeaderAndTrailerToBinaryW(pszString, cchString,
1019 1020
     CERT_HEADER_START_W, CERT_TRAILER_START_W, pbBinary, pcbBinary,
     pdwSkip, FALSE);
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031

    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,
     CERT_REQUEST_HEADER_W, CERT_REQUEST_TRAILER_W, pbBinary, pcbBinary,
1032
     pdwSkip, TRUE);
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042

    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,
1043
     X509_HEADER_W, X509_TRAILER_W, pbBinary, pcbBinary, pdwSkip, TRUE);
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 1104 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 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163

    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;

    TRACE("(%s, %d, %08x, %p, %p, %p, %p)\n", debugstr_w(pszString),
     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)
        cchString = strlenW(pszString);
    ret = decoder(pszString, cchString, pbBinary, pcbBinary, pdwSkip, pdwFlags);
    if (ret)
        SetLastError(ret);
    return (ret == ERROR_SUCCESS) ? TRUE : FALSE;
}