diff --git a/src/main.zig b/src/main.zig index 72509b6..a830a36 100644 --- a/src/main.zig +++ b/src/main.zig @@ -1,6 +1,7 @@ const std = @import("std"); const b64 = @import("base64.zig"); const hex = @import("hex.zig"); +const xor = @import("xor.zig"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; @@ -28,4 +29,23 @@ pub fn main() !void { try stdout.print("{s}", .{result}); } } + + if (std.mem.eql(u8, args[1], "xor")) { + const in_a = args[2]; + const in_b = args[3]; + + const buf_a = try hex.decode(allocator, in_a); + defer allocator.free(buf_a); + + const buf_b = try hex.decode(allocator, in_b); + defer allocator.free(buf_b); + + const out = try xor.xor_buffers(allocator, buf_a, buf_b); + defer allocator.free(out); + + const out_hex = try hex.encode(allocator, out); + defer allocator.free(out_hex); + + try stdout.print("{s}", .{out_hex}); + } } diff --git a/src/xor.zig b/src/xor.zig new file mode 100644 index 0000000..762a095 --- /dev/null +++ b/src/xor.zig @@ -0,0 +1,14 @@ +const std = @import("std"); + +/// buf_a ^ buf_b. Caller must free result. +pub fn xor_buffers(allocator: std.mem.Allocator, buf_a: []u8, buf_b: []u8) ![]u8 { + if (buf_a.len != buf_b.len) return error.UnequalLength; + + var out: []u8 = try allocator.alloc(u8, buf_a.len); + + for (0..buf_a.len) |i| { + out[i] = buf_a[i] ^ buf_b[i]; + } + + return out; +}