Zig Requires Chilkat v11.0.0+
Zig
RSA Encrypt RSA/ECB/OAEPWithSHA1AndMGF1Padding
See more RSA Examples
Demonstrates how to RSA encrypt using RSA/ECB/OAEPWithSHA1AndMGF1Padding. Also demonstrates RSA/ECB/OAEPWithSHA-256AndMGF1Padding. Both of these terms are from Java's JCE. Note: In this context, "ECB" doesn't actually mean anything. It's a symmetric cipher mode that doesn't apply (or make sense) in this context.Chilkat Zig Downloads
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();
// First load a public key object with a public key.
// In this case, we'll load it from a file.
const pubkey = try chilkat.PublicKey.init();
defer pubkey.deinit();
pubkey.loadFromFile("qa_data/pem/rsa_public.pem") catch {
std.debug.print("{s}\n", .{try pubkey.getLastErrorText(alloc)});
return;
};
// RSA encryption is limited to small amounts of data. The limit
// is typically a few hundred bytes and is based on the key size and
// padding (OAEP vs. PKCS1_5). RSA encryption is typically used for
// encrypting hashes or symmetric (bulk encryption algorithm) secret keys.
const plain_text = "Time is an illusion. Lunchtime doubly so.";
// Import the public key to be used for encrypting.
try rsa.usePublicKey(pubkey);
// To get OAEP padding, set the PkcsPadding property equal to false
rsa.setPkcsPadding(false);
rsa.setOaepHash("sha256");
// Indicate we'll want hex output
rsa.setEncodingMode("hex");
// Encrypt..
const use_private_key = false;
const encrypted_str = try rsa.encryptStringENC(alloc, plain_text, use_private_key);
std.debug.print("{s}\n", .{encrypted_str});
// -------------------------------------------------
// Now decrypt with the matching private key.
const rsa2 = try chilkat.Rsa.init();
defer rsa2.deinit();
const priv_key = try chilkat.PrivateKey.init();
defer priv_key.deinit();
priv_key.loadEncryptedPem("qa_data/pem/rsa_passwd.pem", "passwd") catch {
std.debug.print("{s}\n", .{try priv_key.getLastErrorText(alloc)});
return;
};
try rsa2.usePrivateKey(priv_key);
// Make sure we have the same settings used for encryption.
rsa2.setPkcsPadding(false);
rsa2.setEncodingMode("hex");
rsa2.setOaepHash("sha256");
const original_str = try rsa2.decryptStringENC(alloc, encrypted_str, true);
std.debug.print("{s}\n", .{original_str});
}