| 1 | // derived from pacman base64.c (brainspark b.v., 2006-2010) and signing.c. |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | module engine |
| 4 | |
| 5 | fn signature_base64_value(value u8) int { |
| 6 | return match value { |
| 7 | `A`...`Z` { int(value - `A`) } |
| 8 | `a`...`z` { int(value - `a`) + 26 } |
| 9 | `0`...`9` { int(value - `0`) + 52 } |
| 10 | `+` { 62 } |
| 11 | `/` { 63 } |
| 12 | `=` { 64 } |
| 13 | else { 127 } |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | pub fn decode_signature(input string) ![]u8 { |
| 18 | text := c_string_prefix(input) |
| 19 | mut symbols := 0 |
| 20 | mut padding := 0 |
| 21 | for index, value in text { |
| 22 | if value == `\r` && index + 1 < text.len && text[index + 1] == `\n` { continue } |
| 23 | if value == `\n` { continue } |
| 24 | decoded := signature_base64_value(value) |
| 25 | if value == `=` { padding++ } |
| 26 | if decoded == 127 || padding > 2 || (decoded < 64 && padding != 0) { |
| 27 | return AlpmError{ kind: .sig_invalid, detail: 'invalid base64 signature' } |
| 28 | } |
| 29 | symbols++ |
| 30 | } |
| 31 | // line-only input must not expose the C decoder's uninitialized allocation. |
| 32 | if symbols == 0 { return []u8{} } |
| 33 | capacity := text.len / 4 * 3 + text.len % 4 * 3 / 4 |
| 34 | required := symbols / 4 * 3 + ((symbols % 4 * 6 + 7) >> 3) |
| 35 | if capacity < required { |
| 36 | return AlpmError{ kind: .sig_invalid, detail: 'incomplete base64 signature' } |
| 37 | } |
| 38 | mut output := []u8{cap: capacity} |
| 39 | mut accumulated := u32(0) |
| 40 | mut count := 0 |
| 41 | mut remaining := 3 |
| 42 | for value in text { |
| 43 | if value in [`\r`, `\n`] { continue } |
| 44 | decoded := signature_base64_value(value) |
| 45 | if decoded == 64 { remaining-- } |
| 46 | accumulated = (accumulated << 6) | u32(decoded & 63) |
| 47 | count++ |
| 48 | if count == 4 { |
| 49 | if remaining > 0 { output << u8(accumulated >> 16) } |
| 50 | if remaining > 1 { output << u8(accumulated >> 8) } |
| 51 | if remaining > 2 { output << u8(accumulated) } |
| 52 | count = 0 |
| 53 | } |
| 54 | } |
| 55 | return output |
| 56 | } |
| 57 | |