3 Copyright (C) 2002 Niels Möller
5 This file is part of GNU Nettle.
7 GNU Nettle is free software: you can redistribute it and/or
8 modify it under the terms of either:
10 * the GNU Lesser General Public License as published by the Free
11 Software Foundation; either version 3 of the License, or (at your
12 option) any later version.
16 * the GNU General Public License as published by the Free
17 Software Foundation; either version 2 of the License, or (at your
18 option) any later version.
20 or both in parallel, as here.
22 GNU Nettle is distributed in the hope that it will be useful,
23 but WITHOUT ANY WARRANTY; without even the implied warranty of
24 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
25 General Public License for more details.
27 You should have received copies of the GNU General Public License and
28 the GNU Lesser General Public License along with this program. If
29 not, see http://www.gnu.org/licenses/.
41 #define TABLE_INVALID -1
42 #define TABLE_SPACE -2
46 base64_decode_init(struct base64_decode_ctx *ctx)
48 static const signed char base64_decode_table[0x100] =
50 /* White space is HT, VT, FF, CR, LF and SPC */
51 -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -2, -2, -2, -2, -1, -1,
52 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
53 -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
54 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -3, -1, -1,
55 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
56 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
57 -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
58 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
59 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
60 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
61 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
62 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
63 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
64 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
65 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
66 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
69 ctx->word = ctx->bits = ctx->padding = 0;
70 ctx->table = base64_decode_table;
74 base64_decode_single(struct base64_decode_ctx *ctx,
78 int data = ctx->table[src];
83 assert(data >= 0 && data < 0x40);
88 ctx->word = ctx->word << 6 | data;
94 dst[0] = ctx->word >> ctx->bits;
106 /* There can be at most two padding characters. */
107 if (!ctx->bits || ctx->padding > 2)
110 if (ctx->word & ( (1<<ctx->bits) - 1))
111 /* We shouldn't have any leftover bits */
121 base64_decode_update(struct base64_decode_ctx *ctx,
130 for (i = 0, done = 0; i<src_length; i++)
131 switch(base64_decode_single(ctx, dst + done, src[i]))
144 assert(done <= BASE64_DECODE_LENGTH(src_length));
151 base64_decode_final(struct base64_decode_ctx *ctx)
153 return ctx->bits == 0;