Skip to content

Advanced Topics & Recipes

Eldric Arlo Bennett edited this page Nov 14, 2025 · 1 revision

Advanced Topics & Recipes

This section is designed to answer the advanced questions developers will encounter when deploying an application using Oracipher Core in the real world. It provides practical strategies and code patterns for error handling, security lifecycle management, and performance optimization.


Error Handling Strategies

A robust application must gracefully handle failures and provide meaningful feedback to the user. The error codes in hsc_kernel.h are precise for developers but should be translated into simpler messages for end-users.

Recipe: Mapping Error Codes to User-Friendly Messages

The following table provides a strategy for interpreting the most common error codes and suggests appropriate user-facing messages.

Error Code Technical Meaning Recommended User-Facing Message
HSC_ERROR_FILE_IO The library failed to read from or write to a file. "Error: Could not access the specified file. Please check that the file exists and you have the correct permissions."
HSC_ERROR_ALLOCATION_FAILED A memory allocation (standard or secure) failed. "Error: The application ran out of memory. Please close other programs and try again."
HSC_ERROR_INVALID_FORMAT The input data (e.g., certificate, encrypted file) is corrupted or not in the expected format. "Error: The input file is invalid or corrupted. It could not be processed."
HSC_ERROR_CRYPTO_OPERATION A low-level cryptographic operation failed. For decryption, this almost always means a key mismatch or data tampering. "Decryption Failed: The data could not be decrypted. This may be due to an incorrect key, or the file may have been tampered with."
HSC_ERROR_CERT_CHAIN_OR_VALIDITY The recipient's certificate could not be validated against the trusted CA, is expired, or is not yet valid. "Verification Failed: The recipient's certificate is invalid or could not be trusted. The operation has been aborted."
HSC_ERROR_CERT_SUBJECT_MISMATCH The identity (Common Name) in the certificate does not match the expected identity. "Verification Failed: The recipient's identity does not match the expected user. The operation has been aborted to prevent a potential impersonation attack."
HSC_ERROR_CERT_REVOKED_OR_OCSP_FAILED The certificate has been revoked by the CA, or its revocation status could not be confirmed (fail-closed policy). "Verification Failed: The recipient's certificate has been revoked or its status could not be verified. The operation has been aborted for your security."

Implementation Example:

Here is a C function demonstrating how to wrap a library call and handle its errors.

void process_decryption_for_user(const char* in_path, const char* out_path, /*...other args...*/) {
    // ... setup recipient_kp, sender_pk etc. ...

    int result = hsc_hybrid_decrypt_stream_raw(out_path, in_path, sender_pk, recipient_kp);

    switch (result) {
        case HSC_OK:
            printf("Success! File decrypted to %s\n", out_path);
            break;
        
        case HSC_ERROR_CRYPTO_OPERATION:
            fprintf(stderr, "Decryption Failed: The data could not be decrypted. This may be due to an incorrect key, or the file may have been tampered with.\n");
            break;
            
        case HSC_ERROR_INVALID_FORMAT:
            fprintf(stderr, "Error: The encrypted file appears to be invalid or corrupted.\n");
            break;
            
        case HSC_ERROR_FILE_IO:
            fprintf(stderr, "Error: Could not read the encrypted file or write the decrypted file. Check permissions.\n");
            break;
            
        default:
            fprintf(stderr, "An unexpected error occurred (Code: %d).\n", result);
            break;
    }
}

Key Rotation & Revocation: A Production Playbook

In a production environment, keys and certificates have a lifecycle. They must be managed, and you must have a plan for when they are compromised.

Scenario: A User's Private Key is Suspected to be Compromised

If a user (e.g., Alice) believes her private key has been lost, stolen, or otherwise compromised, the following steps must be taken immediately to protect her identity and data.

Emergency Playbook:

  1. Step 1: Revoke the Old Certificate (Immediate Action)

    • Action: The user must immediately contact the Certificate Authority (CA) that issued her certificate (alice.pem) and request its revocation.
    • Mechanism: The CA will update its Online Certificate Status Protocol (OCSP) responder. From this point forward, any Oracipher Core client attempting to verify Alice's old certificate will receive a "revoked" status from the OCSP server.
    • Library Behavior: The hsc_verify_user_certificate() function will detect this and return HSC_ERROR_CERT_REVOKED_OR_OCSP_FAILED, automatically preventing anyone from encrypting new data for this compromised identity.
  2. Step 2: Generate a New Master Key Pair (Rotation)

    • Action: Alice must generate a completely new key pair on a secure machine. The old key pair should be securely deleted and never used again.
    • Library Function: hsc_master_key_pair* kp = hsc_generate_master_key_pair();
  3. Step 3: Issue a New Certificate

    • Action: Using her new key pair, Alice must generate a new CSR and submit it to the CA.
    • Library Functions:
      1. hsc_generate_csr(kp, "alice@example.com", &csr_pem);
      2. Submit the CSR to the CA to get a new alice_new.pem.
  4. Step 4: Distribute the New Public Certificate

    • Action: Alice must distribute her new public certificate (alice_new.pem) to her contacts so they can begin encrypting new messages for her new, secure identity.

Important Note: Revoking a certificate only prevents future messages from being encrypted with the compromised key. Any data that was previously encrypted with the old key is still vulnerable if the attacker has both the old private key and the old encrypted data.


Performance Deep Dive: Streaming vs. One-Shot Encryption

Oracipher Core offers two distinct APIs for symmetric encryption. Choosing the right one is critical for application performance and scalability.

Feature One-Shot AEAD API Streaming API
API Functions hsc_aead_encrypt()
hsc_aead_decrypt()
hsc_crypto_stream_... functions
Ideal Use Case Small, self-contained data: session tokens, encrypted configuration values, database fields, short messages. Large files (videos, backups, disk images), network data streams, or any situation where the data size is unknown or memory is constrained.
Memory Footprint Proportional to data size. The entire plaintext message must be loaded into memory before encryption can begin. Constant and very low. Data is processed in fixed-size chunks (HSC_FILE_IO_CHUNK_SIZE), so you can encrypt a 100 GB file with only a few kilobytes of RAM.
Performance Profile Slightly faster for very small data due to lower initialization overhead. Becomes inefficient and memory-intensive as data size grows. Has a tiny one-time cost to initialize the stream state. Performance is constant and scales linearly regardless of the total file size.
Data Overhead Fixed overhead per message:
HSC_AEAD_OVERHEAD_BYTES (40 bytes total for nonce + tag).
Header + per-chunk overhead:
HSC_STREAM_HEADER_BYTES (24 bytes) once, plus a small tag for each chunk.

Recipe: When to Choose Which API?

  • Use the One-Shot AEAD API (hsc_aead_*) if:

    • You are certain your data will always be relatively small (e.g., less than 1 MB).
    • Your application can comfortably afford to load the entire message into memory.
  • Use the Streaming API (hsc_crypto_stream_*) if:

    • You are encrypting files that could be larger than a few megabytes.
    • You are working in a memory-constrained environment (like an embedded device).
    • You are processing a network stream where the total data size is not known in advance.

General Guideline: When in doubt, prefer the Streaming API. It is the more scalable and robust solution. A sensible threshold for switching from one-shot to streaming is around 1 megabyte (1 MB). Below this size, the convenience of the one-shot API may be preferable; above it, the memory efficiency of the streaming API becomes a clear advantage.

Clone this wiki locally