Something went wrong. Try again.
Sign git commits and tags with an OpenPGP key kept in Bitwarden.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Making a version 4 detached signature over binary data, RFC 9580//! sections 5.2.3 and 5.2.4.//!//! The work is split the way the program is split. Whoever has the data//! builds the hashed part of the packet with `hashedPart`, runs the data and//! it through `Hasher`, and assembles the packet with `writePacket`. Whoever//! has the secret key turns the digest into signature material with//! `signDigest`. The shim does the first and the agent the second, so the//! data never goes to the agent and the key never leaves it.//!//! The digest is always SHA-512, which is what GnuPG 2.4 picks for these keys//! and which RFC 9580 allows for every algorithm here.
const std = @import("std");const testing = std.testing;const Sha512 = std.crypto.hash.sha2.Sha512;const Ed25519 = std.crypto.sign.Ed25519;const rsa = @import("std_crypto_ext").rsa;
const packet = @import("packet.zig");const key_mod = @import("key.zig");const Algorithm = key_mod.Algorithm;
/// The hash algorithm identifier for SHA-512, RFC 9580 section 9.5.pub const hash_algorithm_sha512: u8 = 10;
/// Signature type 0x00, a signature of a binary document.const sig_type_binary: u8 = 0x00;
pub const digest_length = Sha512.digest_length;
/// The longest signature material: one MPI as wide as the largest RSA modulus.pub const max_material = 2 + rsa.max_modulus_len;
/// What goes into the signature besides the signature itself: who made it,/// with what, and when.pub const Params = struct { created: u32, algorithm: Algorithm, fingerprint: [20]u8,};
/// Version, type, algorithms, and the hashed subpackets: the issuer's/// fingerprint (33) and the creation time (2).const hashed_part_len = 4 + 2 + (1 + 1 + 1 + 20) + (1 + 1 + 4);
/// The part of the packet body covered by the hash, from the version octet to/// the end of the hashed subpackets.pub fn hashedPart(p: Params) [hashed_part_len]u8 { var buf: [hashed_part_len]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); w.writeAll(&.{ 4, sig_type_binary, @backingInt(p.algorithm), hash_algorithm_sha512 }) catch unreachable; w.writeInt(u16, hashed_part_len - 6, .big) catch unreachable; // Issuer fingerprint: length, type, key version, fingerprint. w.writeAll(&.{ 22, 33, 4 }) catch unreachable; w.writeAll(&p.fingerprint) catch unreachable; // Signature creation time. w.writeAll(&.{ 5, 2 }) catch unreachable; w.writeInt(u32, p.created, .big) catch unreachable; std.debug.assert(w.end == buf.len); return buf;}
/// Hashes the data being signed and then the signature's own trailer.pub const Hasher = struct { sha: Sha512,
pub fn init() Hasher { return .{ .sha = .init(.{}) }; }
pub fn update(h: *Hasher, data: []const u8) void { h.sha.update(data); }
/// Hashes the trailer of section 5.2.4 and returns the digest. pub fn final(h: *Hasher, p: Params) [digest_length]u8 { const hashed = hashedPart(p); h.sha.update(&hashed); var trailer: [6]u8 = .{ 4, 0xff, 0, 0, 0, 0 }; std.mem.writeInt(u32, trailer[2..6], hashed.len, .big); h.sha.update(&trailer); var digest: [digest_length]u8 = undefined; h.sha.final(&digest); return digest; }};
pub const SignError = error{ /// The key could not produce a signature: an Ed25519 key whose halves /// disagree, or an RSA signature that failed its own check. SigningFailed,};
/// Signs `digest` with the signing key `key`, writing the algorithm-specific/// signature material into `out` and returning it.////// For EdDSALegacy that is two MPIs, R and S; for Ed25519 the 64 raw octets;/// for RSA one MPI, the signature value. In OpenPGP the EdDSA "message" is the/// digest itself, not the data.pub fn signDigest(key: *const key_mod.ComponentKey, digest: [digest_length]u8, out: *[max_material]u8) SignError![]u8 { var w: std.Io.Writer = .fixed(out); switch (key.secret) { .ed25519 => |ed| { const pair = Ed25519.KeyPair.generateDeterministic(ed.seed) catch return error.SigningFailed; var sig = (pair.sign(&digest, null) catch return error.SigningFailed).toBytes(); defer std.crypto.secureZero(u8, &sig); if (key.algorithm == .ed25519) { w.writeAll(&sig) catch unreachable; } else { packet.writeMpi(&w, sig[0..32]) catch unreachable; packet.writeMpi(&w, sig[32..64]) catch unreachable; } }, .rsa => |r| { const sk = rsa.SecretKey.fromComponents(r.n, r.e, r.d) catch return error.SigningFailed; var sig_buf: [rsa.max_modulus_len]u8 = undefined; const sig = rsa.pkcs1v1_5.Signer(Sha512).signDigest(&sig_buf, digest, sk) catch return error.SigningFailed; packet.writeMpi(&w, sig) catch unreachable; }, } return w.buffered();}
/// Writes the whole signature packet, header and all.pub fn writePacket( w: *std.Io.Writer, p: Params, digest: [digest_length]u8, material: []const u8,) std.Io.Writer.Error!void { const hashed = hashedPart(p); // Unhashed: the 8-octet issuer key ID (16), for verifiers that predate // the fingerprint subpacket. const unhashed_len = 1 + 1 + 8; const body_len = hashed.len + 2 + unhashed_len + 2 + material.len; try packet.writeHeader(w, .signature, body_len); try w.writeAll(&hashed); try w.writeInt(u16, unhashed_len, .big); try w.writeAll(&.{ 9, 16 }); try w.writeAll(p.fingerprint[12..20]); // The first two octets of the digest, a quick check for verifiers. try w.writeAll(digest[0..2]); try w.writeAll(material);}
const testing_keys = @import("testing_keys.zig");
fn signForTest(gpa: std.mem.Allocator, key: *const key_mod.Key, data: []const u8, created: u32) ![]u8 { const signing = key.primary(); const params: Params = .{ .created = created, .algorithm = signing.algorithm, .fingerprint = signing.fingerprint }; var h: Hasher = .init(); h.update(data); const digest = h.final(params); var material_buf: [max_material]u8 = undefined; const material = try signDigest(signing, digest, &material_buf); var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); try writePacket(&out.writer, params, digest, material); return out.toOwnedSlice();}
test "Ed25519 signatures are deterministic and verify" { const gpa = testing.allocator; const bytes = try testing_keys.buildEd25519Native(gpa, testing_keys.native_seed, 1767225600); var key = try key_mod.Key.parse(gpa, bytes); defer key.deinit(gpa);
const a = try signForTest(gpa, &key, "hello\n", 1767225600); defer gpa.free(a); const b = try signForTest(gpa, &key, "hello\n", 1767225600); defer gpa.free(b); try testing.expectEqualSlices(u8, a, b);
// Take the packet apart again and check the signature against the // public key with std's verifier. var it: packet.Iterator = .{ .bytes = a }; const p = (try it.next()).?; try testing.expectEqual(packet.Tag.signature, p.tag); const sig_bytes = p.body[p.body.len - 64 ..]; const signing = key.primary(); var h: Hasher = .init(); h.update("hello\n"); const digest = h.final(.{ .created = 1767225600, .algorithm = signing.algorithm, .fingerprint = signing.fingerprint }); try testing.expectEqualSlices(u8, digest[0..2], p.body[p.body.len - 66 ..][0..2]); const sig = Ed25519.Signature.fromBytes(sig_bytes[0..64].*); try sig.verify(&digest, try Ed25519.PublicKey.fromBytes(signing.secret.ed25519.public));}
test "RSA signatures verify under the public key" { const gpa = testing.allocator; const armor = @import("armor.zig"); const block = try armor.decode(gpa, testing_keys.rsa2048.armored); var key = try key_mod.Key.parse(gpa, block.data); defer key.deinit(gpa);
const pkt = try signForTest(gpa, &key, "hello\n", 1767225600); defer gpa.free(pkt);
var it: packet.Iterator = .{ .bytes = pkt }; const p = (try it.next()).?; var r: packet.Reader = .{ .bytes = p.body[hashed_part_len + 2 + 10 + 2 ..] }; const sig = try r.takeMpi(); try testing.expect(r.atEnd());
const signing = key.primary(); var h: Hasher = .init(); h.update("hello\n"); const digest = h.final(.{ .created = 1767225600, .algorithm = signing.algorithm, .fingerprint = signing.fingerprint }); const public = try rsa.PublicKey.fromBytes(signing.secret.rsa.n, signing.secret.rsa.e); // The MPI dropped any leading zeros; the verifier wants the full width. var full: [256]u8 = @splat(0); @memcpy(full[256 - sig.len ..], sig); try rsa.pkcs1v1_5.Signer(Sha512).verifyDigest(&full, digest, public);}