// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! OpenPGP ASCII armor, RFC 9580 section 6. //! //! Armor is base64 between a `-----BEGIN PGP ...-----` line and the matching //! `END` line, with optional `Key: value` headers and an optional CRC-24 //! checksum line starting with `=`. RFC 9580 makes the checksum optional and //! tells writers not to rely on it, but GnuPG 2.4 still writes one and older //! verifiers expect it, so `encode` writes one and `decode` checks it when it //! is there. const std = @import("std"); const Allocator = std.mem.Allocator; const testing = std.testing; pub const Error = error{ /// There is no `-----BEGIN PGP ` line, or no matching `END` line. MalformedArmor, /// The body is not valid base64. InvalidBase64, /// The checksum line does not match the body. ChecksumMismatch, }; /// What an armored block decoded to: the label after `BEGIN PGP ` and the /// binary it carried. pub const Block = struct { /// `PRIVATE KEY BLOCK`, `SIGNATURE`, and so on. Points into the input. label: []const u8, /// Owned by the caller, from the allocator passed to `decode`. data: []u8, }; /// CRC-24 as RFC 9580 section 6.1 defines it. pub fn crc24(data: []const u8) u24 { var crc: u32 = 0xB704CE; for (data) |byte| { crc ^= @as(u32, byte) << 16; for (0..8) |_| { crc <<= 1; if (crc & 0x1000000 != 0) crc ^= 0x1864CFB; } } return @truncate(crc); } /// Decodes the first armored block in `text`. /// /// Text before the `BEGIN` line is ignored, since a key pasted into a note is /// as likely as not to have a line of explanation above it. pub fn decode(gpa: Allocator, text: []const u8) (Error || Allocator.Error)!Block { const begin_prefix = "-----BEGIN PGP "; const dashes = "-----"; const begin = std.mem.find(u8, text, begin_prefix) orelse return error.MalformedArmor; const label_start = begin + begin_prefix.len; const label_len = std.mem.find(u8, text[label_start..], dashes) orelse return error.MalformedArmor; const label = text[label_start..][0..label_len]; var lines = std.mem.splitScalar(u8, text[label_start + label_len + dashes.len ..], '\n'); // The rest of the BEGIN line. _ = lines.next(); // Headers run until the first blank line. A block with no headers still // has the blank line, but some writers drop it; a line that does not // look like `Key: value` is taken as the start of the body. var body_start: ?[]const u8 = null; while (lines.next()) |raw| { const line = std.mem.trimEnd(u8, raw, " \t\r"); if (line.len == 0) break; if (std.mem.find(u8, line, ": ") == null) { body_start = line; break; } } var body: std.ArrayList(u8) = .empty; defer body.deinit(gpa); var checksum: ?[]const u8 = null; var ended = false; var pending = body_start; while (true) { const line = if (pending) |p| blk: { pending = null; break :blk p; } else std.mem.trimEnd(u8, lines.next() orelse break, " \t\r"); if (std.mem.startsWith(u8, line, "-----END PGP ")) { const rest = line["-----END PGP ".len..]; if (!std.mem.startsWith(u8, rest, label) or !std.mem.eql(u8, rest[label.len..], dashes)) { return error.MalformedArmor; } ended = true; break; } if (line.len > 0 and line[0] == '=') { checksum = line[1..]; continue; } try body.appendSlice(gpa, std.mem.trim(u8, line, " \t")); } if (!ended) return error.MalformedArmor; const decoder = std.base64.standard.Decoder; const size = decoder.calcSizeForSlice(body.items) catch return error.InvalidBase64; const data = try gpa.alloc(u8, size); errdefer gpa.free(data); decoder.decode(data, body.items) catch return error.InvalidBase64; if (checksum) |c| { var crc_bytes: [3]u8 = undefined; if (c.len != 4) return error.ChecksumMismatch; decoder.decode(&crc_bytes, c) catch return error.ChecksumMismatch; if (std.mem.readInt(u24, &crc_bytes, .big) != crc24(data)) return error.ChecksumMismatch; } // The body is base64 of what may be secret key material. std.crypto.secureZero(u8, body.items); return .{ .label = label, .data = data }; } /// Writes `data` as an armored block labelled `label`, with lines of 64 /// characters and a CRC-24 line, the way GnuPG writes them. pub fn encode(w: *std.Io.Writer, label: []const u8, data: []const u8) std.Io.Writer.Error!void { try w.print("-----BEGIN PGP {s}-----\n\n", .{label}); const encoder = std.base64.standard.Encoder; // 48 bytes of input is 64 characters of output. var i: usize = 0; while (i < data.len) : (i += 48) { const chunk = data[i..@min(i + 48, data.len)]; var line: [64]u8 = undefined; try w.writeAll(encoder.encode(&line, chunk)); try w.writeByte('\n'); } var crc_bytes: [3]u8 = undefined; std.mem.writeInt(u24, &crc_bytes, crc24(data), .big); var crc_text: [4]u8 = undefined; try w.print("={s}\n", .{encoder.encode(&crc_text, &crc_bytes)}); try w.print("-----END PGP {s}-----\n", .{label}); } test "crc24 of the empty string is the initial value" { try testing.expectEqual(@as(u24, 0xB704CE), crc24("")); } test "encode and decode round trip, with and without the checksum" { const gpa = testing.allocator; var data: [200]u8 = undefined; for (&data, 0..) |*b, i| b.* = @truncate(i * 7); var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); try encode(&out.writer, "SIGNATURE", &data); const text = out.written(); try testing.expect(std.mem.startsWith(u8, text, "-----BEGIN PGP SIGNATURE-----\n\n")); const block = try decode(gpa, text); defer gpa.free(block.data); try testing.expectEqualStrings("SIGNATURE", block.label); try testing.expectEqualSlices(u8, &data, block.data); // Without the checksum line, and with CRLF endings, a comment above the // block and a header inside it. var crlf: std.ArrayList(u8) = .empty; defer crlf.deinit(gpa); try crlf.appendSlice(gpa, "my signing key\r\n"); var it = std.mem.splitScalar(u8, text, '\n'); var first = true; while (it.next()) |line| { if (line.len > 0 and line[0] == '=') continue; try crlf.appendSlice(gpa, line); try crlf.appendSlice(gpa, "\r\n"); if (first) { try crlf.appendSlice(gpa, "Comment: hello\r\n"); first = false; } } const block2 = try decode(gpa, crlf.items); defer gpa.free(block2.data); try testing.expectEqualSlices(u8, &data, block2.data); } test "a wrong checksum or a mismatched END line is rejected" { const gpa = testing.allocator; try testing.expectError(error.ChecksumMismatch, decode(gpa, \\-----BEGIN PGP SIGNATURE----- \\ \\AAEC \\=AAAA \\-----END PGP SIGNATURE----- )); try testing.expectError(error.MalformedArmor, decode(gpa, \\-----BEGIN PGP SIGNATURE----- \\ \\AAEC \\-----END PGP MESSAGE----- )); try testing.expectError(error.MalformedArmor, decode(gpa, "no armor here")); }