const std = @import("std");
const c = @cImport({
    @cInclude("openssl/rsa.h");
    @cInclude("openssl/bn.h");
    @cInclude("openssl/err.h");
    @cInclude("arpa/inet.h");
});

const stdout = std.io.getStdOut().writer();

fn print(comptime str: []const u8, args: anytype) void {
    stdout.print(str, args) catch unreachable;
}

fn println(comptime str: []const u8, args: anytype) void {
    print(str ++ "\n", args);
}

fn create_bn_from_dec_string(str: []const u8) ?*c.BIGNUM {
    var n: ?*c.BIGNUM = c.BN_new();
    if (n == null) {
        println("Failed to create BIGNUM.", .{});
        std.os.exit(1);
    }

    if (c.BN_dec2bn(@alignCast(@ptrCast(&n)), @ptrCast(str)) == 0) {
        println("Failed to convert dec to BIGNUM.", .{});
        std.os.exit(1);
    }

    return n;
}

pub fn main() !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();

    var alloc = arena.allocator();

    var e: ?*c.BIGNUM = create_bn_from_dec_string("65537");
    var pubkey: ?*c.BIGNUM = create_bn_from_dec_string("7405872386298001828045412304885395957447735855540402226273272018863616985100578690399814241980651881616439657049448993379923363875365701026162288146836853");

    var _result_str = "16B33257CF7E2CF19E62B814538CACFC2AD77851DBF18E9299C057EA1FF46336DAB290D3805EA45C2A827E387EC9D6F558D6C0A3C1C740C35BE8696195E70B0B";
    var result_str = try alloc.alloc(u8, _result_str.len);
    @memcpy(result_str, _result_str);

    const args = try std.process.argsAlloc(alloc);

    if (args.len == 3) {
        if (args[1].len != _result_str.len) {
            println("Lol wrong args", .{});
            return;
        }
        println("Using {s}", .{args[1]});
        @memcpy(result_str, args[1]);
        pubkey = create_bn_from_dec_string(args[2]);
    }

    var ans = try alloc.alloc(u8, result_str.len / 2);
    defer alloc.free(ans);

    for (0..(result_str.len / 2)) |i| {
        var ti = i * 2;
        var r = try std.fmt.parseInt(u8, result_str[ti..(ti + 2)], 16);
        ans[i] = r;
    }

    println("ans: {any}", .{ans});

    var rsa: ?*c.RSA = c.RSA_new();
    if (rsa == null) {
        println("Failed to init rsa", .{});
        return;
    }
    defer c.RSA_free(rsa);

    if (c.RSA_set0_key(rsa, pubkey, e, null) != 1) {
        println("Failed to set the key", .{});
        return;
    }

    //var size = c.RSA_size(rsa);
    //println("RSA size: {}", .{size});

    var englishwords = std.mem.split(u8, @embedFile("english.txt"), "\r\n");

    //var err_buff = try alloc.alloc(u8, 1024);
    //defer alloc.free(err_buff);

    var test_r = try alloc.alloc(u8, 64);
    defer alloc.free(test_r);

    var test_buf = try alloc.alloc(u8, 64);
    defer alloc.free(test_buf);

    while (englishwords.next()) |word| {
        if (word.len == 0) {
            continue;
        }
        @memset(test_buf, 0);
        var start = test_buf.len - word.len;
        for (word, 0..) |char, i| {
            test_buf[start + i] = char;
        }
        if (c.RSA_public_encrypt(@intCast(test_buf.len), @ptrCast(test_buf.ptr), @ptrCast(test_r.ptr), rsa, c.RSA_NO_PADDING) == -1) {
            var err = c.ERR_get_error();
            var err_buff = c.ERR_error_string(err, null);
            println("Failed to encrypt! {} err: {s}", .{ err, err_buff });
            std.os.exit(1);
        }
        if (std.mem.startsWith(u8, test_r, ans)) {
            println("found {s}", .{word});
            for (test_r) |byte| {
                print("{x:0>2}", .{byte});
            }
            print("\n", .{});
            std.os.exit(0);
        }
    }
}
