Safe API Framework
Layered API framework for safety-related applications (ERTMS RBC reference targeting CENELEC EN 50128 SIL 4)
Loading...
Searching...
No Matches
Checksum Module - User Guide

What is Checksum?

  • The Checksum module provides data integrity verification. It computes
  • CRC32 or simple checksum to detect accidental data corruption.
  • Key idea: Know when data is corrupted. Don't silently process bad data.

Quick Start

  • c
  • #include "safeapi/checksum/sapi_checksum.h"
  • // Compute checksum
  • uint32_t crc = sapi_checksum_crc32(data, length);
  • // Verify checksum
  • uint32_t stored_crc = get_stored_checksum();
  • if (crc != stored_crc) {
  • log_error("Data corrupted: CRC mismatch");
  • SAPI_SAFESTATE(SAPI_SAFESTATE_LEVEL_SAFE, REASON);
  • }

Functions

  • c
  • // Compute CRC32 of entire buffer
  • uint32_t sapi_checksum_crc32(const uint8_t *data, size_t length);
  • // Simple 8-bit checksum (XOR of all bytes)
  • uint8_t sapi_checksum_xor8(const uint8_t *data, size_t length);
  • // CRC16 for smaller data
  • uint16_t sapi_checksum_crc16(const uint8_t *data, size_t length);

Practical Examples

  • ### Example 1: Message Integrity Check
  • c
  • typedef struct {
  • uint32_t command_id;
  • uint8_t data[256];
  • uint32_t checksum; // Computed over all previous fields
  • } message_t;
  • sapi_status_t process_message(const message_t *msg) {
  • // Compute checksum over everything except checksum field
  • uint32_t computed = sapi_checksum_crc32((const uint8_t *)msg,
  • offsetof(message_t, checksum));
  • if (computed != msg->checksum) {
  • log_error("Message corrupted");
  • return SAPI_STATUS_INVALID_PARAM;
  • }
  • execute_command(msg->command_id, msg->data);
  • return SAPI_STATUS_OK;
  • }
  • ### Example 2: Configuration Validation
  • c
  • typedef struct {
  • uint32_t version;
  • char device_name[32];
  • uint32_t timeout_ms;
  • uint32_t crc; // Checksum of above
  • } config_t;
  • sapi_status_t load_config(config_t *cfg) {
  • // Read from Non-Volatile Memory
  • read_nvm(0, (uint8_t *)cfg, sizeof(config_t));
  • // Verify checksum
  • size_t data_len = offsetof(config_t, crc);
  • uint32_t computed = sapi_checksum_crc32((const uint8_t *)cfg, data_len);
  • if (computed != cfg->crc) {
  • log_error("Configuration corrupted, using defaults");
  • init_default_config(cfg);
  • }
  • return SAPI_STATUS_OK;
  • }

Best Practices

  • 1. Use CRC32 for Large Data
  • - Better collision detection
  • - Slightly slower but worth it
  • 2. Checksum Storage
  • - Store checksum with data
  • - Compute over all data except checksum field
  • - Verify on load/receive
  • 3. When to Verify
  • - After receiving over network
  • - After reading from storage
  • - Before executing critical commands
  • 4. Handling Corruption
  • - Don't try to "fix" corrupted data
  • - Log the corruption
  • - Either reload from backup or trigger safe-state

See Also