// derived from pacman base64.c (brainspark b.v., 2006-2010) and signing.c. // SPDX-License-Identifier: GPL-2.0-or-later module engine fn signature_base64_value(value u8) int { return match value { `A`...`Z` { int(value - `A`) } `a`...`z` { int(value - `a`) + 26 } `0`...`9` { int(value - `0`) + 52 } `+` { 62 } `/` { 63 } `=` { 64 } else { 127 } } } pub fn decode_signature(input string) ![]u8 { text := c_string_prefix(input) mut symbols := 0 mut padding := 0 for index, value in text { if value == `\r` && index + 1 < text.len && text[index + 1] == `\n` { continue } if value == `\n` { continue } decoded := signature_base64_value(value) if value == `=` { padding++ } if decoded == 127 || padding > 2 || (decoded < 64 && padding != 0) { return AlpmError{ kind: .sig_invalid, detail: 'invalid base64 signature' } } symbols++ } // line-only input must not expose the C decoder's uninitialized allocation. if symbols == 0 { return []u8{} } capacity := text.len / 4 * 3 + text.len % 4 * 3 / 4 required := symbols / 4 * 3 + ((symbols % 4 * 6 + 7) >> 3) if capacity < required { return AlpmError{ kind: .sig_invalid, detail: 'incomplete base64 signature' } } mut output := []u8{cap: capacity} mut accumulated := u32(0) mut count := 0 mut remaining := 3 for value in text { if value in [`\r`, `\n`] { continue } decoded := signature_base64_value(value) if decoded == 64 { remaining-- } accumulated = (accumulated << 6) | u32(decoded & 63) count++ if count == 4 { if remaining > 0 { output << u8(accumulated >> 16) } if remaining > 1 { output << u8(accumulated >> 8) } if remaining > 2 { output << u8(accumulated) } count = 0 } } return output }