Sample code for 30+ languages & platforms
Zig

Encrypt / Decrypt Secure Strings

See more Encryption Examples

Demonstrates how to use the EncryptSecureENC and DecryptSecureENC methods to encrypt/decrypt secure strings. These methods were added in Chilkat v9.5.0.71 (released January 2018).

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // Load the secure string with some text.
    const sec_str1 = try chilkat.SecureString.init();
    defer sec_str1.deinit();
    sec_str1.loadFile("qa_data/txt/helloWorld.txt", "utf-8") catch {
        std.debug.print("Failed to load helloWorld.txt\n", .{});
        return;
    };

    const crypt = try chilkat.Crypt2.init();
    defer crypt.deinit();

    crypt.setCryptAlgorithm("aes");
    crypt.setCipherMode("cbc");
    crypt.setKeyLength(128);
    crypt.setEncodedKey("000102030405060708090A0B0C0D0E0F", "hex");
    crypt.setEncodedIV("000102030405060708090A0B0C0D0E0F", "hex");
    crypt.setEncodingMode("base64");

    // Return the base64 encoded encrypted contents of secStr1.
    const encrypted_str = try crypt.encryptSecureENC(alloc, sec_str1);
    std.debug.print("Encrypted string: {s}\n", .{encrypted_str});

    // Output:
    // Encrypted string: qiq+IFhcjTkEIkZyf31V/g==

    // Decrypt to secStr2:
    const sec_str2 = try chilkat.SecureString.init();
    defer sec_str2.deinit();
    crypt.decryptSecureENC(encrypted_str, sec_str2) catch {};

    // Access the contents of secStr2
    std.debug.print("Decrypted string: {s}\n", .{try sec_str2.access(alloc)});

    // Output:
    // Decrypted string: Hello World!
}