Sample code for 30+ languages & platforms
Zig Requires Chilkat v11.0.0+

RSA Encrypt and Decrypt Credit Card Numbers

See more RSA Examples

_LANGUAGE_ sample code to RSA public-key encrypt and decrypt credit card numbers. The RSA key is loaded from an unencrypted PKCS8 file. Chilkat provides many ways of setting the key -- loading from both encrypted and unencrypted PEM, PKCS8, DER, PVK, etc. Keys may be loaded from files or in-memory representations. (The RSA component also provides the ability to generate RSA keys.)

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 assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    const rsa = try chilkat.Rsa.init();
    defer rsa.deinit();

    const priv_key = try chilkat.PrivateKey.init();
    defer priv_key.deinit();

    // Load an RSA private key from a file:
    priv_key.loadAnyFormatFile("rsaPrivateKey.key", "") catch {
        std.debug.print("{s}\n", .{try priv_key.getLastErrorText(alloc)});
        return;
    };

    // Get the public part of the private key.
    const pub_key = try chilkat.PublicKey.init();
    defer pub_key.deinit();
    priv_key.toPublicKey(pub_key) catch {};

    rsa.usePublicKey(pub_key) catch {
        std.debug.print("{s}\n", .{try rsa.getLastErrorText(alloc)});
        return;
    };

    // Encrypt a VISA credit card number:
    // 1234-5678-0000-9999
    const cc_number = "1234567800009999";

    var use_private_key: bool = false;
    rsa.setEncodingMode("base64");
    const encrypted_str = try rsa.encryptStringENC(alloc, cc_number, use_private_key);
    std.debug.print("Encrypted:\n", .{});
    std.debug.print("{s}\n", .{encrypted_str});

    // Now decrypt:
    const rsa_decryptor = try chilkat.Rsa.init();
    defer rsa_decryptor.deinit();

    rsa_decryptor.setEncodingMode("base64");
    rsa_decryptor.usePrivateKey(priv_key) catch {};

    use_private_key = true;
    const decrypted_str = try rsa_decryptor.decryptStringENC(alloc, encrypted_str, use_private_key);

    std.debug.print("Decrypted:\n", .{});
    std.debug.print("{s}\n", .{decrypted_str});

    // Important: RSA encryption should only be used to encrypt small amounts of data.
    // It is typically used for encrypting symmetric encryption
    // keys such that a symmetric encryption algorithm, such as
    // AES is then used to encrypt/decrypt bulk data.
}