From eaee6254045d384021af153c9ed91367da1adde7 Mon Sep 17 00:00:00 2001 From: Emil Lerch Date: Fri, 7 Jan 2022 10:28:53 -0800 Subject: [PATCH] add encryption executable code --- src/encrypt.zig | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/encrypt.zig diff --git a/src/encrypt.zig b/src/encrypt.zig new file mode 100644 index 0000000..593c2a8 --- /dev/null +++ b/src/encrypt.zig @@ -0,0 +1,45 @@ +const std = @import("std"); +const crypt = @import("crypt.zig"); + +pub fn main() !u8 { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + var args = std.process.args(); + defer args.deinit(); + var first = true; + while (args.next(allocator)) |arg_or_err| { + const arg = try arg_or_err; + defer allocator.free(arg); + if (first) { + // skip argv[0] + first = false; + continue; + } + const key = try getKey(allocator); + defer allocator.free(key); + const encrypted = try crypt.encryptWithKey(allocator, key.*, arg); + defer allocator.free(encrypted); + try std.io.getStdOut().writeAll(encrypted); + break; + } + + return 0; +} + +fn getKey(allocator: std.mem.Allocator) !*[crypt.key_size]u8 { + const passfile = std.fs.cwd().openFile(".clippy", .{}) catch |e| { + if (e == error.FileNotFound) { + const cwd = std.fs.realpathAlloc(allocator, ".") catch "could not determine"; + defer allocator.free(cwd); + std.log.err("Could not find '.clippy' file in directory {s}. Please add a password to this file", .{cwd}); + } + return e; + }; + defer passfile.close(); + const pass = try passfile.readToEndAlloc(allocator, std.math.maxInt(usize)); + defer allocator.free(pass); + + const tmp_key = try crypt.keyFromPassword(allocator, pass, ""); // reuse key - this is slow + return tmp_key; +}