## Overview
The DAP Crypto module provides comprehensive cryptographic operations and security infrastructure for the DAP ecosystem. This module implements various encryption algorithms, digital signatures, key management, hashing functions, and secure random number generation, ensuring data confidentiality, integrity, and authenticity across all DAP applications.
**Based on:** `dap-sdk/crypto/include/dap_crypto.h`, `dap-sdk/crypto/src/dap_crypto.c`
## Document Structure
- [[#Overview|Overview]]
- [[#Module Structures|Module Structures]]
- [[#dap_enc_t|dap_enc_t - Encryption Context]]
- [[#dap_sign_t|dap_sign_t - Digital Signature]]
- [[#dap_pkey_t|dap_pkey_t - Public/Private Keys]]
- [[#dap_hash_t|dap_hash_t - Hash Operations]]
- [[#dap_random_t|dap_random_t - Random Generation]]
- [[#dap_enc_key_callbacks_t|dap_enc_key_callbacks_t - Encryption Callbacks]]
- [[#dap_sign_type_t|dap_sign_type_t - Signature Type]]
- [[#dap_sign_hdr_t|dap_sign_hdr_t - Signature Header]]
- [[#dap_hash_str_t|dap_hash_str_t - Hash String]]
- [[#dap_cert_metadata_t|dap_cert_metadata_t - Certificate Metadata]]
- [[#dap_cert_t|dap_cert_t - Certificate]]
- [[#Module Functions|Module Functions]]
- [[#Encryption Operations|Symmetric/Asymmetric Encryption]]
- [[#Signature Operations|Digital Signatures]]
- [[#Hash Operations|Cryptographic Hashing]]
- [[#Key Management|Key Generation and Management]]
- [[#Error Codes|Error Codes]]
- [[#Typical Examples|Typical Examples]]
## Module Structures
### dap_enc_t
Core encryption context managing cipher operations and key material.
```c
typedef struct dap_enc {
struct {
dap_enc_key_type_t key_type; // Encryption algorithm type
size_t key_size; // Key size in bytes
size_t block_size; // Cipher block size
bool is_initialized; // Initialization status
uint64_t operations_count; // Number of operations performed
dap_enc_mode_t mode; // Encryption mode (ECB, CBC, etc.)
} pub;
struct {
uint8_t *key_data; // Private key material
uint8_t *iv; // Initialization vector
void *cipher_context; // Algorithm-specific context
pthread_mutex_t enc_mutex; // Thread safety lock
bool is_key_loaded; // Key loading status
uint32_t rounds; // Number of encryption rounds
} priv;
} dap_enc_t;
```
**Public Fields:**
- `key_type` - Encryption algorithm (AES, Salsa20, etc.)
- `key_size` - Size of encryption key in bytes
- `block_size` - Cipher block size for operations
- `mode` - Encryption mode (ECB, CBC, GCM, etc.)
- `operations_count` - Counter for performed operations
**Private Fields:**
- `key_data` - Sensitive key material (securely stored)
- `iv` - Initialization vector for modes requiring it
- `cipher_context` - Algorithm-specific implementation context
- `is_key_loaded` - Flag indicating key material availability
### dap_sign_t
Digital signature context for creating and verifying signatures.
```c
typedef struct dap_sign {
struct {
dap_sign_type_t type; // Signature algorithm type
size_t signature_size; // Signature length in bytes
size_t key_size; // Key size for algorithm
bool is_valid; // Signature validity status
dap_time_t created_time; // Signature creation timestamp
} pub;
struct {
dap_pkey_t *private_key; // Private key for signing
dap_pkey_t *public_key; // Public key for verification
uint8_t *signature_data; // Signature bytes
dap_hash_type_t hash_type; // Hash algorithm used
void *sign_context; // Algorithm-specific context
bool is_deterministic; // Deterministic signing flag
} priv;
} dap_sign_t;
```
**Signature Management:**
- `type` - Signature algorithm (RSA, ECDSA, EdDSA, etc.)
- `signature_size` - Length of generated signatures
- `created_time` - Timestamp for signature creation
- `private_key`/`public_key` - Key pair for signing operations
- `hash_type` - Hash function used in signature process
### dap_pkey_t
Public/private key structure for asymmetric cryptography.
```c
typedef struct dap_pkey {
struct {
dap_pkey_type_t type; // Key algorithm type
size_t key_size; // Key size in bits
bool is_private; // Private key flag
bool is_valid; // Key validity status
dap_time_t created_time; // Key creation timestamp
char *key_id; // Human-readable key identifier
} pub;
struct {
uint8_t *key_data; // Raw key material
size_t key_data_size; // Size of key data
void *key_context; // Algorithm-specific context
uint32_t reference_count; // Reference counter
bool is_hardware_backed; // Hardware security module flag
dap_enc_t *encryption_context; // Associated encryption context
} priv;
} dap_pkey_t;
```
### dap_hash_t
Hash operation context for cryptographic hashing.
```c
typedef struct dap_hash {
struct {
dap_hash_type_t type; // Hash algorithm type
size_t hash_size; // Output hash size in bytes
size_t block_size; // Hash block size
uint64_t total_length; // Total bytes processed
bool is_finalized; // Hash finalization status
} pub;
struct {
void *hash_context; // Algorithm-specific context
uint8_t *intermediate_hash; // Intermediate hash value
uint8_t *final_hash; // Final hash output
pthread_mutex_t hash_mutex; // Thread safety lock
bool supports_incremental; // Incremental hashing support
uint32_t update_count; // Number of updates performed
} priv;
} dap_hash_t;
```
### dap_random_t
Random number generation context for cryptographic randomness.
```c
typedef struct dap_random {
struct {
dap_random_type_t type; // Random number generator type
bool is_seeded; // Seeding status
uint64_t bytes_generated; // Total random bytes generated
dap_time_t last_reseed; // Last reseeding timestamp
uint32_t entropy_level; // Available entropy level
} pub;
struct {
void *rng_context; // RNG algorithm context
uint8_t *entropy_pool; // Entropy accumulation pool
size_t entropy_pool_size; // Size of entropy pool
pthread_mutex_t random_mutex; // Thread safety lock
bool is_hardware_rng; // Hardware RNG availability
uint32_t reseed_counter; // Automatic reseed counter
} priv;
} dap_random_t;
```
### dap_enc_key_callbacks_t
Encryption key callbacks structure for algorithm-specific operations.
```c
typedef struct dap_enc_key_callbacks {
const char *name; // Algorithm name
dap_enc_callback_dataop_t enc; // Encryption callback
dap_enc_callback_dataop_t dec; // Decryption callback
dap_enc_callback_dataop_na_t enc_na; // Non-allocating encryption
dap_enc_callback_dataop_na_t dec_na; // Non-allocating decryption
dap_enc_callback_dataop_na_ext_t dec_na_ext; // Extended non-allocating decryption
dap_enc_callback_sign_op_t sign_get; // Signature creation callback
dap_enc_callback_sign_op_t sign_verify; // Signature verification callback
dap_enc_callback_gen_key_public_t gen_key_public; // Public key generation
dap_enc_callback_calc_out_size enc_out_size; // Encryption output size calculation
dap_enc_callback_calc_out_size dec_out_size; // Decryption output size calculation
dap_enc_gen_bob_shared_key gen_bob_shared_key; // Bob's shared key generation
dap_enc_gen_alice_shared_key gen_alice_shared_key; // Alice's shared key generation
dap_enc_callback_serialize_t ser_sign; // Signature serialization
dap_enc_callback_serialize_t ser_priv_key; // Private key serialization
dap_enc_callback_serialize_t ser_pub_key; // Public key serialization
dap_enc_callback_key_size_t ser_pub_key_size; // Public key size calculation
dap_enc_callback_key_size_t ser_priv_key_size; // Private key size calculation
dap_enc_callback_deserialize_t deser_sign; // Signature deserialization
dap_enc_callback_deserialize_t deser_priv_key; // Private key deserialization
dap_enc_callback_deserialize_t deser_pub_key; // Public key deserialization
dap_enc_callback_key_size_t deser_sign_size; // Deserialized signature size
dap_enc_callback_key_size_t deser_pub_key_size; // Deserialized public key size
dap_enc_callback_key_size_t deser_priv_key_size; // Deserialized private key size
dap_enc_callback_new new_callback; // Key creation callback
dap_enc_callback_data_t new_from_data_public_callback; // Public key from data
dap_enc_callback_new_generate new_generate_callback; // Key generation callback
dap_enc_callback_new delete_callback; // Key deletion callback
dap_enc_callback_delete del_sign; // Signature deletion
dap_enc_callback_delete del_pub_key; // Public key deletion
dap_enc_callback_delete del_priv_key; // Private key deletion
} dap_enc_key_callbacks_t;
```
**Callback Functions:**
- `name` - Human-readable algorithm name
- `enc`/`dec` - Basic encryption/decryption operations
- `enc_na`/`dec_na` - Non-allocating operations for performance
- `sign_get`/`sign_verify` - Digital signature operations
- `gen_key_public` - Public key generation from private key
- `ser_*`/`deser_*` - Serialization and deserialization callbacks
- `new_callback`/`delete_callback` - Key lifecycle management
### dap_sign_type_t
Digital signature type union for type-safe signature handling.
```c
typedef union dap_sign_type {
dap_sign_type_enum_t type; // Signature type enumeration
uint32_t raw; // Raw type value
} DAP_ALIGN_PACKED dap_sign_type_t;
```
**Fields:**
- `type` - Typed signature type enumeration
- `raw` - Raw 32-bit type value for direct manipulation
### dap_sign_hdr_t
Digital signature header structure for signature metadata.
```c
typedef struct dap_sign_hdr {
dap_sign_type_t type; // Signature type
uint8_t hash_type; // Hash algorithm used
uint8_t padding; // Padding for alignment
uint32_t sign_size; // Signature data size
uint32_t sign_pkey_size; // Serialized public key size
} DAP_ALIGN_PACKED dap_sign_hdr_t;
```
**Header Fields:**
- `type` - Signature algorithm type
- `hash_type` - Hash function used in signature process
- `sign_size` - Size of signature data in bytes
- `sign_pkey_size` - Size of serialized public key
### dap_sign_t
Complete digital signature structure for blockchain storage.
```c
typedef struct dap_sign {
dap_sign_hdr_t header; // Signature header metadata
uint8_t pkey_n_sign[]; // Public key and signature data
} DAP_ALIGN_PACKED dap_sign_t;
```
**Signature Structure:**
- `header` - Signature metadata and type information
- `pkey_n_sign` - Variable-length array containing public key and signature
### dap_hash_str_t
Hash string structure for formatted hash representation.
```c
typedef struct dap_hash_str {
char s[DAP_HASH_FAST_STR_SIZE]; // Hash string buffer
} dap_hash_str_t;
```
**Fields:**
- `s` - Fixed-size buffer for hexadecimal hash string representation
### dap_cert_metadata_t
Certificate metadata structure for extended certificate information.
```c
typedef struct dap_cert_metadata {
const char *key; // Metadata key name
uint32_t length; // Value length in bytes
dap_cert_metadata_type_t type; // Metadata value type
byte_t value[]; // Variable-length value data
} dap_cert_metadata_t;
```
**Metadata Fields:**
- `key` - Metadata field identifier
- `length` - Size of value data in bytes
- `type` - Type of metadata value (string, bool, int, etc.)
- `value` - Variable-length metadata value
### dap_cert_t
Certificate structure for digital certificate management.
```c
typedef struct dap_cert {
dap_enc_key_t *enc_key; // Associated encryption key
char name[DAP_CERT_ITEM_NAME_MAX]; // Certificate name
void *_pvt; // Private certificate data
dap_binary_tree_t *metadata; // Certificate metadata tree
} dap_cert_t;
```
**Certificate Fields:**
- `enc_key` - Encryption key associated with certificate
- `name` - Human-readable certificate name
- `_pvt` - Private certificate implementation data
- `metadata` - Binary tree containing certificate metadata
## Module Functions
### Encryption Operations
#### `dap_enc_new()`
Creates new encryption context for cryptographic operations.
```c
dap_enc_t* dap_enc_new(dap_enc_key_type_t a_key_type);
```
**Parameters:**
- `a_key_type` (dap_enc_key_type_t) - Encryption algorithm type
**Returns:**
- `dap_enc_t*` - New encryption context
- `NULL` - Creation failed or unsupported algorithm
**Error Conditions:**
- Returns NULL if a_key_type is invalid or unsupported
- Returns NULL if memory allocation fails
- Returns NULL if algorithm initialization fails
**Description:** Creates a new encryption context for the specified algorithm. The context must be configured with a key before performing encryption operations.
#### `dap_enc_key_new_generate()`
Generates new cryptographic key for encryption context.
```c
int dap_enc_key_new_generate(dap_enc_t *a_enc, const void *a_kex_buf, size_t a_kex_size, const void *a_seed, size_t a_seed_size, size_t a_key_size);
```
**Parameters:**
- `a_enc` (dap_enc_t*) - Encryption context
- `a_kex_buf` (const void*) - Key exchange buffer
- `a_kex_size` (size_t) - Size of key exchange buffer
- `a_seed` (const void*) - Random seed for key generation
- `a_seed_size` (size_t) - Size of random seed
- `a_key_size` (size_t) - Desired key size in bytes
**Returns:**
- `0` - Key generation successful
- `-1` - Invalid parameters or context
- `-2` - Key generation failed
- `-3` - Insufficient entropy
**Error Conditions:**
- Returns -1 if a_enc is NULL or uninitialized
- Returns -2 if random number generation fails
- Returns -3 if insufficient entropy available
#### `dap_enc_encrypt()`
Encrypts data using configured encryption context.
```c
size_t dap_enc_encrypt(dap_enc_t *a_enc, const void *a_in, size_t a_in_size, void *a_out, size_t a_out_size_max);
```
**Parameters:**
- `a_enc` (dap_enc_t*) - Configured encryption context
- `a_in` (const void*) - Input data to encrypt
- `a_in_size` (size_t) - Size of input data
- `a_out` (void*) - Output buffer for encrypted data
- `a_out_size_max` (size_t) - Maximum size of output buffer
**Returns:**
- `size_t` - Number of bytes written to output buffer
- `0` - Encryption failed
**Error Conditions:**
- Returns 0 if encryption context is not properly initialized
- Returns 0 if output buffer is too small
- Returns 0 if encryption algorithm fails
#### `dap_enc_decrypt()`
Decrypts data using configured encryption context.
```c
size_t dap_enc_decrypt(dap_enc_t *a_enc, const void *a_in, size_t a_in_size, void *a_out, size_t a_out_size_max);
```
**Parameters:**
- `a_enc` (dap_enc_t*) - Configured encryption context
- `a_in` (const void*) - Input encrypted data
- `a_in_size` (size_t) - Size of encrypted data
- `a_out` (void*) - Output buffer for decrypted data
- `a_out_size_max` (size_t) - Maximum size of output buffer
**Returns:**
- `size_t` - Number of bytes written to output buffer
- `0` - Decryption failed
### Signature Operations
#### `dap_sign_new()`
Creates new digital signature context.
```c
dap_sign_t* dap_sign_new(dap_sign_type_t a_type);
```
**Parameters:**
- `a_type` (dap_sign_type_t) - Digital signature algorithm type
**Returns:**
- `dap_sign_t*` - New signature context
- `NULL` - Creation failed
**Error Conditions:**
- Returns NULL if a_type is unsupported
- Returns NULL if memory allocation fails
#### `dap_sign_create()`
Creates digital signature for data.
```c
int dap_sign_create(dap_sign_t *a_sign, const void *a_data, size_t a_data_size, void *a_signature, size_t *a_signature_size);
```
**Parameters:**
- `a_sign` (dap_sign_t*) - Configured signature context
- `a_data` (const void*) - Data to sign
- `a_data_size` (size_t) - Size of data to sign
- `a_signature` (void*) - Output buffer for signature
- `a_signature_size` (size_t*) - Input: buffer size, Output: signature size
**Returns:**
- `0` - Signature created successfully
- `-1` - Invalid parameters
- `-2` - Signature creation failed
#### `dap_sign_verify()`
Verifies digital signature against data.
```c
int dap_sign_verify(dap_sign_t *a_sign, const void *a_data, size_t a_data_size, const void *a_signature, size_t a_signature_size);
```
**Parameters:**
- `a_sign` (dap_sign_t*) - Signature context with public key
- `a_data` (const void*) - Original data
- `a_data_size` (size_t) - Size of original data
- `a_signature` (const void*) - Signature to verify
- `a_signature_size` (size_t) - Size of signature
**Returns:**
- `1` - Signature valid
- `0` - Signature invalid
- `-1` - Verification error
#### `dap_sign_init()`
Initializes the digital signature system.
```c
int dap_sign_init(uint8_t a_sign_hash_type_default);
```
**Parameters:**
- `a_sign_hash_type_default` (uint8_t) - Default hash type for signatures
**Returns:**
- `0` - Initialization successful
- `-1` - Initialization failed
#### `dap_sign_get_size()`
Gets the size of a digital signature.
```c
uint64_t dap_sign_get_size(dap_sign_t *a_chain_sign);
```
**Parameters:**
- `a_chain_sign` (dap_sign_t*) - Signature structure
**Returns:**
- `uint64_t` - Size of signature in bytes
#### `dap_sign_verify_by_pkey()`
Verifies digital signature using public key.
```c
int dap_sign_verify_by_pkey(dap_sign_t *a_chain_sign, const void *a_data, const size_t a_data_size, dap_pkey_t *a_pkey);
```
**Parameters:**
- `a_chain_sign` (dap_sign_t*) - Signature to verify
- `a_data` (const void*) - Original data
- `a_data_size` (const size_t) - Size of original data
- `a_pkey` (dap_pkey_t*) - Public key for verification
**Returns:**
- `1` - Signature valid
- `0` - Signature invalid
- `-1` - Verification error
#### `dap_sign_create_output()`
Creates digital signature output.
```c
int dap_sign_create_output(dap_enc_key_t *a_key, const void *a_data, const size_t a_data_size, void *a_output, size_t *a_output_size);
```
**Parameters:**
- `a_key` (dap_enc_key_t*) - Encryption key for signing
- `a_data` (const void*) - Data to sign
- `a_data_size` (const size_t) - Size of data
- `a_output` (void*) - Output buffer for signature
- `a_output_size` (size_t*) - Input: buffer size, Output: signature size
**Returns:**
- `0` - Signature creation successful
- `-1` - Signature creation failed
#### `dap_sign_create_output_unserialized_calc_size()`
Calculates size for unserialized signature output.
```c
size_t dap_sign_create_output_unserialized_calc_size(dap_enc_key_t *a_key);
```
**Parameters:**
- `a_key` (dap_enc_key_t*) - Encryption key
**Returns:**
- `size_t` - Calculated output size
#### `dap_sign_type_from_key_type()`
Converts key type to signature type.
```c
dap_sign_type_t dap_sign_type_from_key_type(dap_enc_key_type_t a_key_type);
```
**Parameters:**
- `a_key_type` (dap_enc_key_type_t) - Key type
**Returns:**
- `dap_sign_type_t` - Corresponding signature type
#### `dap_sign_type_to_key_type()`
Converts signature type to key type.
```c
dap_enc_key_type_t dap_sign_type_to_key_type(dap_sign_type_t a_chain_sign_type);
```
**Parameters:**
- `a_chain_sign_type` (dap_sign_type_t) - Signature type
**Returns:**
- `dap_enc_key_type_t` - Corresponding key type
#### `dap_sign_get_pkey_hash()`
Gets public key hash from signature.
```c
bool dap_sign_get_pkey_hash(dap_sign_t *a_sign, dap_chain_hash_fast_t *a_sign_hash);
```
**Parameters:**
- `a_sign` (dap_sign_t*) - Signature structure
- `a_sign_hash` (dap_chain_hash_fast_t*) - Output hash
**Returns:**
- `true` - Hash retrieved successfully
- `false` - Hash retrieval failed
#### `dap_sign_compare_pkeys()`
Compares public keys from two signatures.
```c
bool dap_sign_compare_pkeys(dap_sign_t *l_sign1, dap_sign_t *l_sign2);
```
**Parameters:**
- `l_sign1` (dap_sign_t*) - First signature
- `l_sign2` (dap_sign_t*) - Second signature
**Returns:**
- `true` - Keys are identical
- `false` - Keys are different
#### `dap_sign_type_from_str()`
Converts string to signature type.
```c
dap_sign_type_t dap_sign_type_from_str(const char *a_type_str);
```
**Parameters:**
- `a_type_str` (const char*) - String representation of signature type
**Returns:**
- `dap_sign_type_t` - Signature type enumeration
#### `dap_sign_type_is_depricated()`
Checks if signature type is deprecated.
```c
bool dap_sign_type_is_depricated(dap_sign_type_t a_sign_type);
```
**Parameters:**
- `a_sign_type` (dap_sign_type_t) - Signature type to check
**Returns:**
- `true` - Signature type is deprecated
- `false` - Signature type is current
#### `dap_sign_get_information()`
Gets detailed information about signature.
```c
void dap_sign_get_information(dap_sign_t *a_sign, dap_string_t *a_str_out, const char *a_hash_out_type);
```
**Parameters:**
- `a_sign` (dap_sign_t*) - Signature structure
- `a_str_out` (dap_string_t*) - Output string for information
- `a_hash_out_type` (const char*) - Hash output type
**Returns:** None (void function)
#### `dap_sign_get_information_json()`
Gets signature information in JSON format.
```c
void dap_sign_get_information_json(json_object* a_json_arr_reply, dap_sign_t* a_sign, json_object *a_json_out, const char *a_hash_out_type);
```
**Parameters:**
- `a_json_arr_reply` (json_object*) - JSON array for reply
- `a_sign` (dap_sign_t*) - Signature structure
- `a_json_out` (json_object*) - Output JSON object
- `a_hash_out_type` (const char*) - Hash output type
**Returns:** None (void function)
#### `dap_sign_set_pkey_by_hash_callback()`
Sets callback for public key retrieval by hash.
```c
int dap_sign_set_pkey_by_hash_callback(dap_sign_callback_t a_callback);
```
**Parameters:**
- `a_callback` (dap_sign_callback_t) - Callback function
**Returns:**
- `0` - Callback set successfully
- `-1` - Callback setting failed
### Hash Operations
#### `dap_hash_new()`
Creates new hash context for cryptographic hashing.
```c
dap_hash_t* dap_hash_new(dap_hash_type_t a_type);
```
**Parameters:**
- `a_type` (dap_hash_type_t) - Hash algorithm type (SHA256, SHA3, etc.)
**Returns:**
- `dap_hash_t*` - New hash context
- `NULL` - Creation failed
#### `dap_hash_update()`
Updates hash context with additional data.
```c
int dap_hash_update(dap_hash_t *a_hash, const void *a_data, size_t a_data_size);
```
**Parameters:**
- `a_hash` (dap_hash_t*) - Hash context
- `a_data` (const void*) - Data to hash
- `a_data_size` (size_t) - Size of data
**Returns:**
- `0` - Update successful
- `-1` - Hash context invalid or finalized
#### `dap_hash_final()`
Finalizes hash computation and retrieves result.
```c
int dap_hash_final(dap_hash_t *a_hash, void *a_output, size_t a_output_size);
```
**Parameters:**
- `a_hash` (dap_hash_t*) - Hash context
- `a_output` (void*) - Output buffer for hash
- `a_output_size` (size_t) - Size of output buffer
**Returns:**
- `0` - Finalization successful
- `-1` - Output buffer too small
- `-2` - Hash context invalid
#### `dap_chain_hash_fast_from_str()`
Converts string to fast hash.
```c
int dap_chain_hash_fast_from_str(const char *a_hash_str, dap_hash_fast_t *a_hash);
```
**Parameters:**
- `a_hash_str` (const char*) - String representation of hash
- `a_hash` (dap_hash_fast_t*) - Output hash structure
**Returns:**
- `0` - Conversion successful
- `-1` - Conversion failed
#### `dap_chain_hash_fast_from_hex_str()`
Converts hexadecimal string to fast hash.
```c
int dap_chain_hash_fast_from_hex_str(const char *a_hex_str, dap_chain_hash_fast_t *a_hash);
```
**Parameters:**
- `a_hex_str` (const char*) - Hexadecimal string
- `a_hash` (dap_chain_hash_fast_t*) - Output hash structure
**Returns:**
- `0` - Conversion successful
- `-1` - Conversion failed
#### `dap_chain_hash_fast_from_base58_str()`
Converts Base58 string to fast hash.
```c
int dap_chain_hash_fast_from_base58_str(const char *a_base58_str, dap_chain_hash_fast_t *a_hash);
```
**Parameters:**
- `a_base58_str` (const char*) - Base58 string
- `a_hash` (dap_chain_hash_fast_t*) - Output hash structure
**Returns:**
- `0` - Conversion successful
- `-1` - Conversion failed
### Key Management
#### `dap_pkey_new()`
Creates new public/private key context.
```c
dap_pkey_t* dap_pkey_new(dap_pkey_type_t a_type);
```
**Parameters:**
- `a_type` (dap_pkey_type_t) - Key algorithm type
**Returns:**
- `dap_pkey_t*` - New key context
- `NULL` - Creation failed
#### `dap_pkey_generate()`
Generates new key pair.
```c
int dap_pkey_generate(dap_pkey_t *a_pkey, size_t a_key_size, const void *a_seed, size_t a_seed_size);
```
**Parameters:**
- `a_pkey` (dap_pkey_t*) - Key context
- `a_key_size` (size_t) - Key size in bits
- `a_seed` (const void*) - Random seed
- `a_seed_size` (size_t) - Size of seed
**Returns:**
- `0` - Key generation successful
- `-1` - Generation failed
#### `dap_pkey_get_hash()`
Gets hash of public key.
```c
bool dap_pkey_get_hash(dap_pkey_t *a_pkey, dap_chain_hash_fast_t *a_out_hash);
```
**Parameters:**
- `a_pkey` (dap_pkey_t*) - Public key structure
- `a_out_hash` (dap_chain_hash_fast_t*) - Output hash
**Returns:**
- `true` - Hash retrieved successfully
- `false` - Hash retrieval failed
### UUID Functions
#### `dap_uuid_generate_uint128()`
Generates 128-bit UUID.
```c
uint128_t dap_uuid_generate_uint128();
```
**Parameters:** None
**Returns:**
- `uint128_t` - Generated 128-bit UUID
#### `dap_uuid_generate_uint64()`
Generates 64-bit UUID.
```c
uint64_t dap_uuid_generate_uint64();
```
**Parameters:** None
**Returns:**
- `uint64_t` - Generated 64-bit UUID
#### `dap_uuid_generate_nonce()`
Generates cryptographic nonce.
```c
void dap_uuid_generate_nonce(void *a_nonce, size_t a_nonce_size);
```
**Parameters:**
- `a_nonce` (void*) - Output buffer for nonce
- `a_nonce_size` (size_t) - Size of nonce
**Returns:** None (void function)
### GUID Functions
#### `dap_guuid_to_hex_str_()`
Converts GUID to hexadecimal string.
```c
dap_guuid_str_t dap_guuid_to_hex_str_(dap_guuid_t a_guuid);
```
**Parameters:**
- `a_guuid` (dap_guuid_t) - GUID to convert
**Returns:**
- `dap_guuid_str_t` - Hexadecimal string representation
#### `dap_guuid_from_hex_str()`
Converts hexadecimal string to GUID.
```c
dap_guuid_t dap_guuid_from_hex_str(const char *a_hex_str, bool *success);
```
**Parameters:**
- `a_hex_str` (const char*) - Hexadecimal string
- `success` (bool*) - Output: conversion success flag
**Returns:**
- `dap_guuid_t` - Converted GUID
## Error Codes
### Cryptographic Error Codes
```c
typedef enum dap_crypto_error {
DAP_CRYPTO_ERROR_SUCCESS = 0, // Operation successful
DAP_CRYPTO_ERROR_INVALID_PARAM = -1, // Invalid parameter provided
DAP_CRYPTO_ERROR_NO_MEMORY = -2, // Memory allocation failed
DAP_CRYPTO_ERROR_UNSUPPORTED = -3, // Unsupported algorithm
DAP_CRYPTO_ERROR_KEY_INVALID = -4, // Invalid or missing key
DAP_CRYPTO_ERROR_BUFFER_TOO_SMALL = -5, // Output buffer too small
DAP_CRYPTO_ERROR_VERIFICATION_FAILED = -6, // Signature verification failed
DAP_CRYPTO_ERROR_ENTROPY_LOW = -7, // Insufficient entropy
DAP_CRYPTO_ERROR_HARDWARE_FAILURE = -8 // Hardware security module error
} dap_crypto_error_t;
```
## Typical Examples
### Basic Encryption Example
```c
#include "dap_common.h"
#include "dap_crypto.h"
int encryption_example() {
log_it(L_INFO, "=== Basic Encryption Example ===");
// Step 1: Initialize crypto system
if (dap_crypto_init() != 0) {
log_it(L_ERROR, "✗ Failed to initialize crypto system");
return -1;
}
log_it(L_DEBUG, "✓ Crypto system initialized");
// Step 2: Create encryption context
dap_enc_t *enc = dap_enc_new(DAP_ENC_KEY_TYPE_AES256);
if (!enc) {
log_it(L_ERROR, "✗ Failed to create encryption context");
goto cleanup;
}
log_it(L_DEBUG, "✓ AES256 encryption context created");
// Step 3: Generate encryption key
uint8_t seed[32];
dap_random_bytes(seed, sizeof(seed));
if (dap_enc_key_new_generate(enc, NULL, 0, seed, sizeof(seed), 32) != 0) {
log_it(L_ERROR, "✗ Failed to generate encryption key");
goto cleanup_enc;
}
log_it(L_DEBUG, "✓ 256-bit encryption key generated");
// Step 4: Encrypt sample data
const char *plaintext = "Hello DAP SDK - this is a test message for encryption";
size_t plaintext_size = strlen(plaintext);
uint8_t *ciphertext = DAP_NEW_SIZE(uint8_t, plaintext_size + 32); // Extra space for padding
if (!ciphertext) {
log_it(L_ERROR, "✗ Failed to allocate ciphertext buffer");
goto cleanup_enc;
}
size_t encrypted_size = dap_enc_encrypt(enc, plaintext, plaintext_size,
ciphertext, plaintext_size + 32);
if (encrypted_size == 0) {
log_it(L_ERROR, "✗ Encryption failed");
goto cleanup_all;
}
log_it(L_INFO, "✓ Data encrypted: %zu bytes -> %zu bytes", plaintext_size, encrypted_size);
// Step 5: Decrypt data to verify
char *decrypted = DAP_NEW_SIZE(char, plaintext_size + 1);
if (!decrypted) {
log_it(L_ERROR, "✗ Failed to allocate decryption buffer");
goto cleanup_all;
}
size_t decrypted_size = dap_enc_decrypt(enc, ciphertext, encrypted_size,
decrypted, plaintext_size);
if (decrypted_size == 0) {
log_it(L_ERROR, "✗ Decryption failed");
goto cleanup_all;
}
decrypted[decrypted_size] = '\0';
log_it(L_INFO, "✓ Data decrypted successfully: '%s'", decrypted);
// Step 6: Verify integrity
if (strcmp(plaintext, decrypted) == 0) {
log_it(L_INFO, "✓ Encryption/decryption cycle verified successfully");
} else {
log_it(L_ERROR, "✗ Data integrity check failed");
}
cleanup_all:
if (decrypted) DAP_DELETE(decrypted);
if (ciphertext) DAP_DELETE(ciphertext);
cleanup_enc:
dap_enc_delete(enc);
cleanup:
dap_crypto_deinit();
log_it(L_INFO, "✓ Basic encryption example completed");
return 0;
}
```
### Digital Signature Example
```c
#include "dap_common.h"
#include "dap_crypto.h"
int signature_example() {
log_it(L_INFO, "=== Digital Signature Example ===");
// Step 1: Initialize systems
if (dap_crypto_init() != 0) {
log_it(L_ERROR, "✗ Failed to initialize crypto system");
return -1;
}
// Step 2: Create signature context
dap_sign_t *sign = dap_sign_new(DAP_SIGN_TYPE_ECDSA_SHA256);
if (!sign) {
log_it(L_ERROR, "✗ Failed to create signature context");
goto cleanup;
}
log_it(L_DEBUG, "✓ ECDSA signature context created");
// Step 3: Generate key pair
dap_pkey_t *keypair = dap_pkey_new(DAP_PKEY_TYPE_ECDSA);
if (!keypair) {
log_it(L_ERROR, "✗ Failed to create key pair context");
goto cleanup_sign;
}
uint8_t seed[32];
dap_random_bytes(seed, sizeof(seed));
if (dap_pkey_generate(keypair, 256, seed, sizeof(seed)) != 0) {
log_it(L_ERROR, "✗ Failed to generate key pair");
goto cleanup_key;
}
log_it(L_DEBUG, "✓ ECDSA key pair generated (256-bit)");
// Step 4: Configure signature context with keys
if (dap_sign_set_private_key(sign, keypair) != 0) {
log_it(L_ERROR, "✗ Failed to set private key");
goto cleanup_key;
}
// Step 5: Sign data
const char *message = "This message will be digitally signed for authenticity verification";
size_t message_size = strlen(message);
uint8_t signature[128]; // ECDSA signatures are typically 64-72 bytes
size_t signature_size = sizeof(signature);
if (dap_sign_create(sign, message, message_size, signature, &signature_size) != 0) {
log_it(L_ERROR, "✗ Failed to create digital signature");
goto cleanup_key;
}
log_it(L_INFO, "✓ Digital signature created: %zu bytes", signature_size);
// Step 6: Extract public key for verification
dap_pkey_t *public_key = dap_pkey_get_public(keypair);
if (!public_key) {
log_it(L_ERROR, "✗ Failed to extract public key");
goto cleanup_key;
}
// Step 7: Create verification context
dap_sign_t *verify = dap_sign_new(DAP_SIGN_TYPE_ECDSA_SHA256);
if (!verify) {
log_it(L_ERROR, "✗ Failed to create verification context");
goto cleanup_pubkey;
}
if (dap_sign_set_public_key(verify, public_key) != 0) {
log_it(L_ERROR, "✗ Failed to set public key for verification");
goto cleanup_verify;
}
// Step 8: Verify signature
int verify_result = dap_sign_verify(verify, message, message_size, signature, signature_size);
if (verify_result == 1) {
log_it(L_INFO, "✓ Signature verification successful - message is authentic");
} else if (verify_result == 0) {
log_it(L_WARNING, "✗ Signature verification failed - message may be tampered");
} else {
log_it(L_ERROR, "✗ Signature verification error");
}
// Step 9: Test with tampered data
char tampered_message[] = "This message has been tampered with";
verify_result = dap_sign_verify(verify, tampered_message, strlen(tampered_message),
signature, signature_size);
if (verify_result == 0) {
log_it(L_INFO, "✓ Tamper detection working - modified message correctly rejected");
} else {
log_it(L_ERROR, "✗ Tamper detection failed - this should not happen");
}
cleanup_verify:
dap_sign_delete(verify);
cleanup_pubkey:
dap_pkey_delete(public_key);
cleanup_key:
dap_pkey_delete(keypair);
cleanup_sign:
dap_sign_delete(sign);
cleanup:
dap_crypto_deinit();
log_it(L_INFO, "✓ Digital signature example completed");
return 0;
}
```
### Hash Function Example
```c
#include "dap_common.h"
#include "dap_crypto.h"
int hash_example() {
log_it(L_INFO, "=== Cryptographic Hash Example ===");
// Step 1: Initialize crypto system
if (dap_crypto_init() != 0) {
log_it(L_ERROR, "✗ Failed to initialize crypto system");
return -1;
}
// Step 2: Create hash context
dap_hash_t *hash = dap_hash_new(DAP_HASH_TYPE_SHA256);
if (!hash) {
log_it(L_ERROR, "✗ Failed to create SHA256 hash context");
goto cleanup;
}
log_it(L_DEBUG, "✓ SHA256 hash context created");
// Step 3: Hash data in chunks (streaming)
const char *data_parts[] = {
"First part of the data to be hashed. ",
"Second part continues the message. ",
"Final part completes the hash input."
};
for (int i = 0; i < 3; i++) {
if (dap_hash_update(hash, data_parts[i], strlen(data_parts[i])) != 0) {
log_it(L_ERROR, "✗ Failed to update hash with part %d", i + 1);
goto cleanup_hash;
}
log_it(L_DEBUG, "✓ Hash updated with part %d (%zu bytes)", i + 1, strlen(data_parts[i]));
}
// Step 4: Finalize hash and get result
uint8_t hash_result[32]; // SHA256 produces 32-byte hash
if (dap_hash_final(hash, hash_result, sizeof(hash_result)) != 0) {
log_it(L_ERROR, "✗ Failed to finalize hash computation");
goto cleanup_hash;
}
// Step 5: Convert hash to hexadecimal string for display
char hash_hex[65]; // 32 bytes * 2 + null terminator
dap_bin2hex(hash_hex, hash_result, sizeof(hash_result));
hash_hex[64] = '\0';
log_it(L_INFO, "✓ SHA256 hash computed successfully:");
log_it(L_INFO, " Hash: %s", hash_hex);
// Step 6: Demonstrate single-call hashing for comparison
const char *complete_message = "First part of the data to be hashed. "
"Second part continues the message. "
"Final part completes the hash input.";
dap_hash_t *hash2 = dap_hash_new(DAP_HASH_TYPE_SHA256);
if (!hash2) {
log_it(L_ERROR, "✗ Failed to create second hash context");
goto cleanup_hash;
}
uint8_t hash_result2[32];
if (dap_hash_update(hash2, complete_message, strlen(complete_message)) != 0 ||
dap_hash_final(hash2, hash_result2, sizeof(hash_result2)) != 0) {
log_it(L_ERROR, "✗ Failed to compute comparison hash");
dap_hash_delete(hash2);
goto cleanup_hash;
}
// Step 7: Verify both methods produce same result
if (memcmp(hash_result, hash_result2, sizeof(hash_result)) == 0) {
log_it(L_INFO, "✓ Streaming and single-call hashing produce identical results");
} else {
log_it(L_ERROR, "✗ Hash results differ - this indicates an error");
}
dap_hash_delete(hash2);
cleanup_hash:
dap_hash_delete(hash);
cleanup:
dap_crypto_deinit();
log_it(L_INFO, "✓ Hash function example completed");
return 0;
}
```
---
**See also:** [[Module DAP Core|Module DAP Core]], [[Module DAP Net|Module DAP Net]], [[ETC/Architecture Overview|Architecture Overview]]
---
*Based on: `dap-sdk/crypto/include/dap_crypto.h`, `dap-sdk/crypto/src/dap_crypto.c`*