Home Learning Paths ECU Lab Assessments Interview Preparation Arena Pricing Log In Sign Up

ECDSA-P256 Sign and Verify

Pythonecdsa_sign.py
#!/usr/bin/env python3
# ECDSA-P256 firmware signing with RFC 6979 deterministic k
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.backends import default_backend

# Key pair generated once; private key stored in code-signing HSM (never exported)
priv = ec.generate_private_key(ec.SECP256R1(), default_backend())
pub  = priv.public_key()

def sign(data: bytes) -> bytes:
    return priv.sign(data, ec.ECDSA(hashes.SHA256()))

def verify(data: bytes, sig: bytes) -> bool:
    try:
        pub.verify(sig, data, ec.ECDSA(hashes.SHA256()))
        return True
    except Exception:
        return False

firmware = b"ECU_firmware_v3.2" + bytes(1024)
sig = sign(firmware)
print(f"Signature length: {len(sig)} bytes (DER-encoded r+s, 64 bytes raw)")
print(f"Valid:   {verify(firmware, sig)}")
print(f"Tampered: {verify(firmware[:100]+b'X'+firmware[101:], sig)}")

# RFC 6979 deterministic k: same message + key always produces same signature
# Prevents k-reuse attack that has broken deployed automotive ECDSA implementations
# where rand() returned 0 or a predictable value

X.509v3 Certificate Structure for Automotive PKI

FieldContentPurpose
subjectCN=TCU_TYPE_WBA12345_SN001, O=VehicleCo GmbHIdentifies ECU type + VIN + serial; unique per ECU
subjectPublicKeyInfoecPublicKey, P-256 (64-byte)Used for ECDSA verification or TLS ECDH
validitynotBefore/notAfter; ~15 yearsCovers vehicle service life
BasicConstraintscA=FALSELeaf cert cannot sign other certs
KeyUsagedigitalSignature OR keyEncipherment (per purpose)Restricts cert to declared role; prevents misuse
SubjectAlternativeNameURI:urn:automotive:ecuid:0xA3Binds cert to specific ECU service ID

Certificate Chain Validation in ECU Bootloader

Ccert_chain.c
/* Certificate chain validation: leaf → Intermediate CA → Root CA */
/* Root CA public key hash stored in OTP fuses -- tamper-proof */
#include "CertMgmt.h"

CertMgmt_VerifyResultType ValidateCert(const uint8* cert_der, uint32 len)
{
    CertMgmt_CertIdType id;

    if (CertMgmt_ParseX509Cert(cert_der, len, &id) != E_OK)
        return CERTMGMT_VERIFY_PARSE_FAILED;

    /* Verify leaf → Intermediate CA (stored in protected flash) */
    if (CertMgmt_VerifySignature(id, CERTMGMT_SLOT_INT_CA) != CERTMGMT_VERIFY_OK)
        return CERTMGMT_VERIFY_SIG_FAILED;

    /* Verify Intermediate CA → Root CA (hash in OTP fuses) */
    if (CertMgmt_VerifyIntermediateCA(CERTMGMT_SLOT_INT_CA,
                                       CERTMGMT_ROOT_CA_OTP_HASH) != CERTMGMT_VERIFY_OK)
        return CERTMGMT_VERIFY_CHAIN_FAILED;

    if (CertMgmt_CheckValidity(id) != E_OK) return CERTMGMT_VERIFY_EXPIRED;
    if (!CertMgmt_HasKeyUsage(id, CERTMGMT_KU_DIGITAL_SIGNATURE))
        return CERTMGMT_VERIFY_KEY_USAGE_MISMATCH;

    return CERTMGMT_VERIFY_OK;
}

Firmware Signing and OTA Package Workflow

Build → Sign → OTA Package → ECU Verify
  CI/CD Build System
  └── Final binary produced from tagged commit
       │
       ▼
  Code Signing Server (HSM-backed; ECDSA private key never exported)
  ├── hash = SHA-256(firmware_binary)
  ├── (r, s) = ECDSA-P256_sign(hash, code_signing_private_key)
  └── Signed binary = firmware_binary || 0xDEADBEEF || hash[32] || r[32] || s[32] || cert_chain_DER
       │
       ▼
  Package Manifest (JSON):
  {"binaries": [{"name":"SBL","sha256":"aabb.."},{"name":"APP","sha256":"ccdd.."}]}
  └── Sign manifest with same ECDSA key
       │
       ▼
  OTA Package = signed manifest + signed binaries
  Delivered via TLS-secured HTTPS to ECU OTA client
       │
       ▼
  ECU Bootloader verification:
  1. Verify manifest ECDSA signature → OEM root CA (OTP fuses)
  2. For each binary: verify SHA-256 hash matches manifest
  3. Verify each binary's own ECDSA signature
  4. Anti-rollback: new version >= current NVM version counter
  All pass → install; any failure → abort + DEM event + recovery mode

Summary

ECDSA-P256 with deterministic k (RFC 6979) is the automotive firmware signing standard -- 64-byte signatures, 0.1 ms verification, no k-reuse risk. The firmware signing workflow chains SHA-256 → ECDSA → manifest → OTA package, with the ECU bootloader verifying every layer before installation. The Root CA public key hash in OTP fuses is the hardware root of trust: it cannot be overwritten by any OTA update or software attack, making it the last line of defence against malicious firmware installation.

🔬 Deep Dive — Core Concepts Expanded

This section builds on the foundational concepts covered above with additional technical depth, edge cases, and configuration nuances that separate competent engineers from experts. When working on production ECU projects, the details covered here are the ones most commonly responsible for integration delays and late-phase defects.

Key principles to reinforce:

  • Configuration over coding: In AUTOSAR and automotive middleware environments, correctness is largely determined by ARXML configuration, not application code. A correctly implemented algorithm can produce wrong results due to a single misconfigured parameter.
  • Traceability as a first-class concern: Every configuration decision should be traceable to a requirement, safety goal, or architecture decision. Undocumented configuration choices are a common source of regression defects when ECUs are updated.
  • Cross-module dependencies: In tightly integrated automotive software stacks, changing one module's configuration often requires corresponding updates in dependent modules. Always perform a dependency impact analysis before submitting configuration changes.

🏭 How This Topic Appears in Production Projects

  • Project integration phase: The concepts covered in this lesson are most commonly encountered during ECU integration testing — when multiple software components from different teams are combined for the first time. Issues that were invisible in unit tests frequently surface at this stage.
  • Supplier/OEM interface: This is a topic that frequently appears in technical discussions between Tier-1 ECU suppliers and OEM system integrators. Engineers who can speak fluently about these details earn credibility and are often brought into critical design review meetings.
  • Automotive tool ecosystem: Vector CANoe/CANalyzer, dSPACE tools, and ETAS INCA are the standard tools used to validate and measure the correct behaviour of the systems described in this lesson. Familiarity with these tools alongside the conceptual knowledge dramatically accelerates debugging in real projects.

⚠️ Common Mistakes and How to Avoid Them

  1. Assuming default configuration is correct: Automotive software tools ship with default configurations that are designed to compile and link, not to meet project-specific requirements. Every configuration parameter needs to be consciously set. 'It compiled' is not the same as 'it is correctly configured'.
  2. Skipping documentation of configuration rationale: In a 3-year ECU project with team turnover, undocumented configuration choices become tribal knowledge that disappears when engineers leave. Document why a parameter is set to a specific value, not just what it is set to.
  3. Testing only the happy path: Automotive ECUs must behave correctly under fault conditions, voltage variations, and communication errors. Always test the error handling paths as rigorously as the nominal operation. Many production escapes originate in untested error branches.
  4. Version mismatches between teams: In a multi-team project, the BSW team, SWC team, and system integration team may use different versions of the same ARXML file. Version management of all ARXML files in a shared repository is mandatory, not optional.

📊 Industry Note

Engineers who master both the theoretical concepts and the practical toolchain skills covered in this course are among the most sought-after professionals in the automotive software industry. The combination of AUTOSAR standards knowledge, safety engineering understanding, and hands-on configuration experience commands premium salaries at OEMs and Tier-1 suppliers globally.

← PreviousKey Management & DistributionNext →Hands-On: HSM-Based Secure Boot