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 d: ?*c.BIGNUM = create_bn_from_dec_string("1545653943570564246212141988589994139279645559486726912293297140150091598977726717239879077953798120855868459360771804433616650588668281034152580212290153");

    var p: ?*c.BIGNUM = create_bn_from_dec_string("112546167358047505471958486197519319605436748416824057782825895564365669780011");
    var q: ?*c.BIGNUM = create_bn_from_dec_string("65802972772386034028625679514602920156340140357656235951559577501150333990623");

    var result_str = "16B33257CF7E2CF19E62B814538CACFC2AD77851DBF18E9299C057EA1FF46336DAB290D3805EA45C2A827E387EC9D6F558D6C0A3C1C740C35BE8696195E70B0B";

    var chs = try alloc.alloc(u8, result_str.len / 2);

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

    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, d) != 1) {
        println("Failed to set the pub key", .{});
        return;
    }

    if (c.RSA_set0_factors(rsa, p, q) != 1) {
        println("Failed to set the priv key", .{});
        return;
    }

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

    println("{} {any}", .{ chs.len, chs });

    if (c.RSA_private_decrypt(@intCast(chs.len), @ptrCast(chs.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);
    }
    println("{any}\n{s}", .{ test_r, test_r });
}
