| 1 |
|
| 2 |
|
| 3 |
#include <b64_decode.h> |
| 4 |
#include <console/console.h> |
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
static const char cd64[] = "|$$$}rstuvwxyz{$$$$$$$>?@ABCDEFGHIJKLMN" |
| 13 |
"OPQRSTUVW$$$$$$XYZ[\\]^_`abcdefghijklmnopq"; |
| 14 |
|
| 15 |
struct buffer_descriptor { |
| 16 |
const uint8_t *input_buffer; |
| 17 |
size_t data_size; |
| 18 |
size_t input_index; |
| 19 |
}; |
| 20 |
|
| 21 |
#define isalnum(c) ((((c) >= 'a') && ((c) <= 'z')) || \ |
| 22 |
(((c) >= 'A') && ((c) <= 'Z')) || \ |
| 23 |
(((c) >= '0') && ((c) <= '9'))) |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
static int get_next_char(struct buffer_descriptor *bd) |
| 34 |
{ |
| 35 |
uint8_t c; |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
while (bd->input_index < bd->data_size) { |
| 45 |
c = bd->input_buffer[bd->input_index++]; |
| 46 |
|
| 47 |
switch (c) { |
| 48 |
case '=': |
| 49 |
case 0xa: |
| 50 |
case 0xd: |
| 51 |
continue; |
| 52 |
|
| 53 |
default: |
| 54 |
break; |
| 55 |
} |
| 56 |
|
| 57 |
if (!isalnum(c) && (c != '+') && (c != '/')) |
| 58 |
return -1; |
| 59 |
|
| 60 |
return c; |
| 61 |
} |
| 62 |
|
| 63 |
return 0; |
| 64 |
} |
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
size_t b64_decode(const uint8_t *input_data, |
| 72 |
size_t input_length, |
| 73 |
uint8_t *output_data) |
| 74 |
{ |
| 75 |
struct buffer_descriptor bd; |
| 76 |
unsigned int interim = 0; |
| 77 |
size_t output_size = 0; |
| 78 |
|
| 79 |
unsigned int bit_count = 0; |
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
bd.input_buffer = input_data; |
| 86 |
bd.data_size = input_length; |
| 87 |
bd.input_index = 0; |
| 88 |
|
| 89 |
while (1) { |
| 90 |
int v = get_next_char(&bd); |
| 91 |
|
| 92 |
if (v < 0) { |
| 93 |
printk(BIOS_ERR, |
| 94 |
"Incompatible character at offset %zd.\n", |
| 95 |
bd.input_index); |
| 96 |
return 0; |
| 97 |
} |
| 98 |
|
| 99 |
if (!v) |
| 100 |
break; |
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
v = cd64[v - 43] - 62; |
| 107 |
|
| 108 |
if (bit_count >= 2) { |
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
int remaining_bits = 8 - bit_count; |
| 118 |
|
| 119 |
interim <<= remaining_bits; |
| 120 |
interim |= v >> (6 - remaining_bits); |
| 121 |
|
| 122 |
|
| 123 |
output_data[output_size++] = interim & 0xff; |
| 124 |
|
| 125 |
interim = v; |
| 126 |
bit_count -= 2; |
| 127 |
} else { |
| 128 |
interim <<= 6; |
| 129 |
interim |= v; |
| 130 |
bit_count += 6; |
| 131 |
} |
| 132 |
} |
| 133 |
|
| 134 |
return output_size; |
| 135 |
} |