zig-tls

Usage

The 5 examples below are taken from zig-tls's README.

.dependencies = .{
    .tls = .{
        .path = "../zig-tls",
    },
},
const tls = b.dependency("tls", .{
    .target = target,
    .optimize = optimize,
});
exe.root_module.addImport("tls", tls.module("tls"));
const tls = @import("tls");

// Load certificate and key
var cert_key = try tls.config.CertKeyPair.fromFilePathAbsolute(
    allocator,
    io,
    "/path/to/cert.pem",
    "/path/to/key.pem",
);
defer cert_key.deinit(allocator);

// Create TLS connection from stream
const tls_conn = try tls.serverFromStream(stream, .{
    .auth = &cert_key,
});

// Read/write through TLS
const n = try tls_conn.read(buffer);
try tls_conn.write(data);
const tls = @import("tls");

// Load the system trust store (or use tls.config.cert.fromFilePathAbsolute
// to pin a specific root CA bundle).
var roots = try tls.config.cert.fromSystem(allocator);
defer roots.deinit(allocator);

// `stream` is any connected stream (e.g. std.net.Stream) over TCP.
var conn = try tls.clientFromStream(stream, .{
    .host = "example.com", // verified against the server certificate (SNI + hostname)
    .root_ca = roots,
});

try conn.write("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n");
var buffer: [4096]u8 = undefined;
const n = try conn.read(&buffer);
_ = n;
var client = tls.nonblock.Client.init(.{
    .host = "mail.example.com",
    .root_ca = roots,
});
defer client.deinit(); // frees optional P-256 verify table from table_allocator

var send_buf: [tls.output_buffer_len]u8 = undefined;
var recv_buf: [tls.input_buffer_len]u8 = undefined;
var recv_len: usize = 0;

while (!client.done()) {
    const step = try client.run(recv_buf[0..recv_len], &send_buf);
    recv_len -= step.recv_pos;
    // write step.send to the socket; read more ciphertext into recv_buf
    recv_len += try stream.read(recv_buf[recv_len..]);
}
const app_cipher = client.cipher().?;
var conn = tls.nonblock.Connection.init(app_cipher);