Fixed XOR

This commit is contained in:
Armin Friedl 2025-02-08 06:33:30 +01:00
parent efbe8b98dc
commit 067f29127a
2 changed files with 34 additions and 0 deletions

View file

@ -1,6 +1,7 @@
const std = @import("std"); const std = @import("std");
const b64 = @import("base64.zig"); const b64 = @import("base64.zig");
const hex = @import("hex.zig"); const hex = @import("hex.zig");
const xor = @import("xor.zig");
pub fn main() !void { pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var gpa = std.heap.GeneralPurposeAllocator(.{}){};
@ -28,4 +29,23 @@ pub fn main() !void {
try stdout.print("{s}", .{result}); 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});
}
} }

14
src/xor.zig Normal file
View file

@ -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;
}