Skip to content

Generate a ZATCA CSR and private key

A certificate signing request (CSR) contains the identity and public key of your invoicing device. Use it during onboarding to request credentials from ZATCA. This walkthrough creates a CSR and its matching private key locally.

Prepare the inputs

Download csr.properties into a working folder. The sample contains demonstration values and targets the non-production environment. You can run it unchanged to learn the workflow.

For your own device, replace the sample values:

Property What to supply
csr.common.name Your device or solution common name
csr.serial.number The solution serial number in ZATCA's required format
csr.organization.identifier Your organization's VAT identifier
csr.organization.unit.name The branch or organizational unit
csr.organization.name The legal organization name
csr.country.name The country code, such as SA
csr.invoice.type The invoice-type capability code required for your device
csr.location.address The business location
csr.industry.business.category The business activity

Use the current field requirements from the ZATCA developer portal when onboarding a real device. The sample values are not a registration for your business. Keep the CSR environment consistent with the API environment you will use next. The examples replace csr.pem and key.pem if those files already exist.

Run the example

Choose your language, then follow its setup and run instructions.

Install Rust and Cargo, then create a project:

cargo new fatoority-guide
cd fatoority-guide
cargo add fatoora-core

Save the code below as src/main.rs. Put the input files in the project root and run:

cargo run

Download this example.

use fatoora_core::config::Environment;
use fatoora_core::csr::{CsrProperties, SigningKey};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let properties = CsrProperties::from_file("csr.properties")?;
    let key = SigningKey::generate();
    let csr = properties.build(&key, Environment::NonProduction)?;
    std::fs::write("csr.pem", csr.to_pem()?)?;
    std::fs::write("key.pem", key.to_pem()?)?;
    println!("Saved csr.pem and key.pem");
    Ok(())
}

Install the package in your Python environment:

pip install fatoority

Save the code as csr.py beside the input files, then run:

python csr.py

Download this example. See Python setup for package details.

from pathlib import Path
from fatoora import CsrProperties, Environment, SigningKey

with CsrProperties.from_file("csr.properties") as properties:
    with SigningKey.generate() as key:
        with properties.build(key, Environment.NON_PRODUCTION) as csr:
            Path("csr.pem").write_text(csr.to_pem(), encoding="utf-8")
            Path("key.pem").write_text(key.to_pem(), encoding="utf-8")
print("Saved csr.pem and key.pem")

Use Node.js 22 or later. In a new working folder, install the package:

npm install fatoority

Save the code as csr.mjs beside the input files, then run:

node csr.mjs

Download this example. These examples run in Node.js and can also be adapted to TypeScript. In a browser, replace filesystem reads with your application's file input and configure the WASM asset as described in the browser setup. Keep objects in the WASM instance that created them; do not pass them between workers.

import { readFileSync, writeFileSync } from 'node:fs';
import { CsrProperties, Environment, SigningKey } from 'fatoority';

const properties = CsrProperties.fromStr(readFileSync('csr.properties', 'utf8'));
const key = SigningKey.generate();
const csr = properties.build(key, Environment.NonProduction);
writeFileSync('csr.pem', csr.toPem());
writeFileSync('key.pem', key.toPem());
console.log('Saved csr.pem and key.pem');

Use the .NET 8 SDK or later. Create a console application:

dotnet new console -n FatoorityGuide
cd FatoorityGuide
dotnet add package Fatoority

Save the code as Program.cs. Put the input files beside the project file, then run:

dotnet run

Download this example. The using declarations release native objects. Check the supported .NET platforms before deployment.

using Fatoora;

using var properties = CsrProperties.FromStr(File.ReadAllText("csr.properties"));
using var key = SigningKey.Generate();
using var csr = properties.Build(key, ZatcaEnvironment.NonProduction);
File.WriteAllText("csr.pem", csr.ToPem());
File.WriteAllText("key.pem", key.ToPem());
Console.WriteLine("Saved csr.pem and key.pem");

For this desktop example, use JDK 17+ and Gradle 8. Create an empty project folder and download build.gradle.kts and settings.gradle.kts into it. The build uses Maven Central and includes the JSON library needed by the validation example.

Save the code as src/main/kotlin/Main.kt (create the folders first). Put the input files in the project root and run:

gradle run

Download this example. use releases each native object. For an existing project, or Android's separate artifact and file handling, follow Kotlin setup. The binding also supports Maven; its dependency coordinates are listed there.

import com.fatoora.*
import java.io.File

fun main(args: Array<String>) {
    CsrProperties.fromStr(File("csr.properties").readText()).use { properties ->
        SigningKey.generate().use { key ->
            properties.build(key, Environment.NonProduction).use { csr ->
                File("csr.pem").writeText(csr.toPem())
                File("key.pem").writeText(key.toPem())
            }
        }
    }
    println("Saved csr.pem and key.pem")
}

Use JDK 17+ and Maven for this walkthrough. In an empty project folder, save this pom.xml. It includes the library, a JSON parser for the validation example, and the plugin used by the run command.

Save the code as src/main/java/Guide.java (create the folders first). Put the input files beside pom.xml, then run:

mvn compile exec:java

Download this example. Try-with-resources releases native objects. The library itself supports Java 8+; see Java setup for platform prerequisites, Gradle installation, and Android configuration.

import com.fatoora.*;
import java.nio.file.*;
import java.nio.charset.StandardCharsets;

public class Guide {
    static String read(String path) throws java.io.IOException {
        return new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8);
    }
    static void write(String path, String text) throws java.io.IOException {
        Files.write(Paths.get(path), text.getBytes(StandardCharsets.UTF_8));
    }
    public static void main(String[] args) throws Exception {
        try (CsrProperties properties = CsrProperties.fromStr(read("csr.properties"));
             SigningKey key = SigningKey.generate();
             Csr csr = properties.build(key, Environment.NonProduction)) {
            write("csr.pem", csr.toPem());
            write("key.pem", key.toPem());
        }
        System.out.println("Saved csr.pem and key.pem");
    }
}

Download and extract the fatoora-ffi-* archive for your platform from GitHub Releases. Save the example as csr.c in the extracted folder, beside the input files.

On Linux, compile the example and the supplied adapter, then run:

cc -std=c11 -Iinclude csr.c src/fatoora.c -L. -lfatoora_ffi -Wl,-rpath,'$ORIGIN' -o csr
./csr csr.properties

Download this example. For other platforms, follow the C installation and linking reference. The cleanup section releases handles and returned strings, including on failure.

The example saves key.pem and csr.pem. Keep the key private.

#include "fatoora.h"
#include <stdio.h>

static int write_pem(const char *path, const char *pem) {
    FILE *file = fopen(path, "wb");
    if (!file) return 0;
    int written = fputs(pem, file) >= 0;
    return fclose(file) == 0 && written;
}

int main(int argc, char **argv) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s csr.properties\n", argv[0]);
        return 1;
    }
    FatooraCsrProperties *properties = NULL;
    FatooraSigningKey *key = NULL;
    FatooraCsr *csr = NULL;
    FatooraError *error = NULL;
    char *csr_pem = NULL, *key_pem = NULL;
    FatooraStatus status = FATOORA_OK;
    int exit_code = 1;
#define TRY(call) do { status = (call); if (status != FATOORA_OK) goto cleanup; } while (0)
    TRY(fatoora_csr_properties_from_file(argv[1], &properties, &error));
    TRY(fatoora_signing_key_generate(&key, &error));
    TRY(fatoora_csr_properties_build(properties, key, FATOORA_NON_PRODUCTION, &csr, &error));
    TRY(fatoora_csr_to_pem(csr, &csr_pem, &error));
    TRY(fatoora_signing_key_to_pem(key, &key_pem, &error));
    if (!write_pem("key.pem", key_pem) || !write_pem("csr.pem", csr_pem)) {
        fputs("Unable to write key.pem or csr.pem.\n", stderr);
        goto cleanup;
    }
    puts("Saved csr.pem and key.pem");
    exit_code = 0;
cleanup:
    if (status != FATOORA_OK) fprintf(stderr, "Error %d: %s\n", (int)status, fatoora_error_message(error));
    fatoora_string_free(key_pem);
    fatoora_string_free(csr_pem);
    fatoora_csr_free(csr);
    fatoora_signing_key_free(key);
    fatoora_csr_properties_free(properties);
    fatoora_error_free(error);
    return exit_code;
}

Install the command-line tool with cargo install fatoora-cli, or extract a release binary and add it to your PATH. See the CLI guide for platform setup. Run beside your input files:

fatoora csr --csr-config csr.properties --generated-csr csr.pem --private-key key.pem --pem

Check the result

You should have a CSR beginning with -----BEGIN CERTIFICATE REQUEST----- and a key beginning with -----BEGIN PRIVATE KEY-----. The selected example explains where it writes those blocks. The CSR can be submitted for onboarding; keep the private key for signing and do not send it as part of the CSR request.

The examples use PEM text. Some integrations expect base64 DER instead; choose the representation required by the receiving endpoint rather than encoding PEM again.

If something goes wrong

Symptom What to check
Configuration file not found Run from the folder containing csr.properties, or change the path in your example.
Properties cannot be parsed Check spelling, missing values, and the property names in the table above.
Onboarding rejects the request Check business identifiers, the required device fields, OTP, and environment against the portal response.

Next, request credentials and connect to ZATCA. See the CSR reference for additional formats and constructors.