commit a199c8ffaaed38a4b5470c1753bf05bb92824905 Author: cscatgirl Date: Tue Mar 3 17:04:11 2026 -0500 Debug ssh key gen diff --git a/build.zig b/build.zig new file mode 100644 index 0000000..0bbbd53 --- /dev/null +++ b/build.zig @@ -0,0 +1,30 @@ +const std = @import("std"); + +pub fn build(b: *std.Build) void { + const target = b.standardTargetOptions(.{}); + + const optimize = b.standardOptimizeOption(.{}); + + const exe = b.addExecutable(.{ + .name = "crypto", + .root_module = b.createModule(.{ + .root_source_file = b.path("src/main.zig"), + + .target = target, + .optimize = optimize, + }), + }); + + b.installArtifact(exe); + + const run_step = b.step("run", "Run the app"); + + const run_cmd = b.addRunArtifact(exe); + run_step.dependOn(&run_cmd.step); + + run_cmd.step.dependOn(b.getInstallStep()); + + if (b.args) |args| { + run_cmd.addArgs(args); + } +} diff --git a/build.zig.zon b/build.zig.zon new file mode 100644 index 0000000..5d4beba --- /dev/null +++ b/build.zig.zon @@ -0,0 +1,82 @@ +.{ + // This is the default name used by packages depending on this one. For + // example, when a user runs `zig fetch --save `, this field is used + // as the key in the `dependencies` table. Although the user can choose a + // different name, most users will stick with this provided value. + // + // It is redundant to include "zig" in this name because it is already + // within the Zig package namespace. + .name = .crypto, + // This is a [Semantic Version](https://semver.org/). + // In a future version of Zig it will be used for package deduplication. + .version = "0.0.0", + // Together with name, this represents a globally unique package + // identifier. This field is generated by the Zig toolchain when the + // package is first created, and then *never changes*. This allows + // unambiguous detection of one package being an updated version of + // another. + // + // When forking a Zig project, this id should be regenerated (delete the + // field and run `zig build`) if the upstream project is still maintained. + // Otherwise, the fork is *hostile*, attempting to take control over the + // original project's identity. Thus it is recommended to leave the comment + // on the following line intact, so that it shows up in code reviews that + // modify the field. + .fingerprint = 0x6828288510fff01f, + // Changing this has security and trust implications. + // Tracks the earliest Zig version that the package considers to be a + // supported use case. + .minimum_zig_version = "0.15.2", + // This field is optional. + // Each dependency must either provide a `url` and `hash`, or a `path`. + // `zig build --fetch` can be used to fetch all dependencies of a package, recursively. + // Once all dependencies are fetched, `zig build` no longer requires + // internet connectivity. + .dependencies = .{ + // See `zig fetch --save ` for a command-line interface for adding dependencies. + //.example = .{ + // // When updating this field to a new URL, be sure to delete the corresponding + // // `hash`, otherwise you are communicating that you expect to find the old hash at + // // the new URL. If the contents of a URL change this will result in a hash mismatch + // // which will prevent zig from using it. + // .url = "https://example.com/foo.tar.gz", + // + // // This is computed from the file contents of the directory of files that is + // // obtained after fetching `url` and applying the inclusion rules given by + // // `paths`. + // // + // // This field is the source of truth; packages do not come from a `url`; they + // // come from a `hash`. `url` is just one of many possible mirrors for how to + // // obtain a package matching this `hash`. + // // + // // Uses the [multihash](https://multiformats.io/multihash/) format. + // .hash = "...", + // + // // When this is provided, the package is found in a directory relative to the + // // build root. In this case the package's hash is irrelevant and therefore not + // // computed. This field and `url` are mutually exclusive. + // .path = "foo", + // + // // When this is set to `true`, a package is declared to be lazily + // // fetched. This makes the dependency only get fetched if it is + // // actually used. + // .lazy = false, + //}, + }, + // Specifies the set of files and directories that are included in this package. + // Only files and directories listed here are included in the `hash` that + // is computed for this package. Only files listed here will remain on disk + // when using the zig package manager. As a rule of thumb, one should list + // files required for compilation plus any license(s). + // Paths are relative to the build root. Use the empty string (`""`) to refer to + // the build root itself. + // A directory listed here means that all files within, recursively, are included. + .paths = .{ + "build.zig", + "build.zig.zon", + "src", + // For example... + //"LICENSE", + //"README.md", + }, +} diff --git a/src/main.zig b/src/main.zig new file mode 100644 index 0000000..dc635e8 --- /dev/null +++ b/src/main.zig @@ -0,0 +1,197 @@ +const std = @import("std"); +const p: u256 = (1 << 255) - 19; +const Bx: u256 = 15112221349535807912866137220509078750507884956996801852099526895779190960831; +const By: u256 = 46316835694926478169428394003475163141307993866256225615783033011972563869189; +const d: u256 = 37095705934669439343138083508754565189542113879843219016388785533085940283555; +const Point = struct { + x: u256, + y: u256, + z: u256, + t: u256, +}; +const ident = Point{ .x = 0, .y = 1, .z = 1, .t = 0 }; +pub fn main() !void { + var seed: [32]u8 = undefined; + std.crypto.random.bytes(&seed); + var hash = std.crypto.hash.sha2.Sha512.init(.{}); + hash.update(&seed); + const digest = hash.finalResult(); + var scalar = digest[0..32].*; + scalar[0] &= 0b11111100; + scalar[31] &= 0b01111111; + scalar[31] |= 0b01000000; + const int_num: u256 = std.mem.readInt(u256, &scalar, .little); + const B = Point{ .x = Bx, .y = By, .z = 1, .t = mul(Bx, By) }; + const product = scalar_mult(B, int_num); + const final = compress(product); + var gpa: std.heap.DebugAllocator(.{}) = .init; + const alloc = gpa.allocator(); + defer { + _ = gpa.deinit(); + } + var args_it = try std.process.argsWithAllocator(alloc); + defer args_it.deinit(); + _ = args_it.next(); + const user = args_it.next().?; + const pub_pem = try encodePublicKey(alloc, final, user); + const priv_pem = try encodePrivateKey(alloc, seed, final, user); + defer alloc.free(pub_pem); + defer alloc.free(priv_pem); + std.debug.print("{s}", .{priv_pem}); + std.debug.print("{s}", .{pub_pem}); +} +fn scalar_mult(pon: Point, scalar: u256) Point { + var result = ident; + var current = pon; + var s = scalar; + while (s > 0) : (s >>= 1) { + if (s & 1 == 1) { + result = add_points(result, current); + } + current = add_points(current, current); + } + return result; +} +fn add_points(p1: Point, p2: Point) Point { + const a = mul(sub(p1.y, p1.x), sub(p2.y, p2.x)); + const b = mul(add(p1.y, p1.x), add(p2.y, p2.x)); + const c = mul(mul(mul(p1.t, 2), d), p2.t); + const d_in = mul(mul(p1.z, 2), p2.z); + const e = sub(b, a); + const f = sub(d_in, c); + const g = add(d_in, c); + const h = add(b, a); + const x3 = mul(e, f); + const y3 = mul(g, h); + const t3 = mul(e, h); + const z3 = mul(f, g); + return Point{ .x = x3, .y = y3, .t = t3, .z = z3 }; +} +fn add(a: u256, b: u256) u256 { + return (a + b) % p; +} +fn sub(a: u256, b: u256) u256 { + return (a + p - b) % p; +} + +fn mul(a: u256, b: u256) u256 { + const wide = @as(u512, a) * @as(u512, b); + return @intCast(wide % @as(u512, p)); +} +fn modInv(a: u256) u256 { + return modPow(a, p - 2); +} + +fn modPow(base: u256, exp: u256) u256 { + var result: u256 = 1; + var b = base % p; + var e = exp; + while (e > 0) : (e >>= 1) { + if (e & 1 == 1) result = mul(result, b); + b = mul(b, b); + } + return result; +} +fn compress(point: Point) [32]u8 { + const zinv = modInv(point.z); + const x = mul(point.x, zinv); + const y = mul(point.y, zinv); + + var bytes: [32]u8 = undefined; + std.mem.writeInt(u256, &bytes, y, .little); + + bytes[31] |= @as(u8, @intCast(x & 1)) << 7; + + return bytes; +} +fn writeU32(buf: *std.Io.Writer, value: u32) !void { + var bytes: [4]u8 = undefined; + std.mem.writeInt(u32, &bytes, value, .big); + _ = try buf.write(&bytes); +} + +fn writeBytes(buf: *std.Io.Writer, data: []const u8) !void { + try writeU32(buf, @intCast(data.len)); + _ = try buf.write(data); +} + +pub fn encodePublicKey( + allocator: std.mem.Allocator, + public_key: [32]u8, + comment: []const u8, +) ![]u8 { + var wire = std.Io.Writer.Allocating.init(allocator); + defer wire.deinit(); + try writeBytes(&wire.writer, "ssh-ed25519"); + try writeBytes(&wire.writer, &public_key); + + const enc = std.base64.standard.Encoder; + const b64_len = enc.calcSize(wire.writer.buffered().len); + const b64_buf = try allocator.alloc(u8, b64_len); + defer allocator.free(b64_buf); + _ = enc.encode(b64_buf, wire.writer.buffered()); + + return std.fmt.allocPrint(allocator, "ssh-ed25519 {s} {s}\n", .{ b64_buf, comment }); +} + +pub fn encodePrivateKey( + allocator: std.mem.Allocator, + seed: [32]u8, + public_key: [32]u8, + comment: []const u8, +) ![]u8 { + var pubkey_wire = std.Io.Writer.Allocating.init(allocator); + defer pubkey_wire.deinit(); + try writeBytes(&pubkey_wire.writer, "ssh-ed25519"); + try writeBytes(&pubkey_wire.writer, &public_key); + + var private_blob: [64]u8 = undefined; + @memcpy(private_blob[0..32], &seed); + @memcpy(private_blob[32..64], &public_key); + + var check_bytes: [4]u8 = undefined; + std.crypto.random.bytes(&check_bytes); + const check = std.mem.readInt(u32, &check_bytes, .big); + + var priv = std.Io.Writer.Allocating.init(allocator); + defer priv.deinit(); + try writeU32(&priv.writer, check); + try writeU32(&priv.writer, check); + try writeBytes(&priv.writer, "ssh-ed25519"); + try writeBytes(&priv.writer, &public_key); + try writeBytes(&priv.writer, &private_blob); + try writeBytes(&priv.writer, comment); + + var pad: u8 = 1; + while (priv.writer.end % 8 != 0) : (pad += 1) { + try priv.writer.writeByte(pad); + } + + var outer = std.Io.Writer.Allocating.init(allocator); + defer outer.deinit(); + _ = try outer.writer.write("openssh-key-v1\x00"); + try writeBytes(&outer.writer, "none"); + try writeBytes(&outer.writer, "none"); + try writeBytes(&outer.writer, ""); + try writeU32(&outer.writer, 1); + try writeBytes(&outer.writer, pubkey_wire.writer.buffered()); + try writeBytes(&outer.writer, priv.writer.buffered()); + + const enc = std.base64.standard.Encoder; + const b64_len = enc.calcSize(outer.writer.buffered().len); + const b64_buf = try allocator.alloc(u8, b64_len); + defer allocator.free(b64_buf); + _ = enc.encode(b64_buf, outer.writer.buffered()); + + var result = std.Io.Writer.Allocating.init(allocator); + _ = try result.writer.write("-----BEGIN OPENSSH PRIVATE KEY-----\n"); + var i: usize = 0; + while (i < b64_buf.len) : (i += 70) { + const end = @min(i + 70, b64_buf.len); + _ = try result.writer.write(b64_buf[i..end]); + _ = try result.writer.write("\n"); + } + _ = try result.writer.write("-----END OPENSSH PRIVATE KEY-----\n"); + + return result.toOwnedSlice(); +}