> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.adid.dev/llms.txt.
> For full documentation content, see https://docs.adid.dev/llms-full.txt.

# Key Types & Algorithms

IDA supports multiple cryptographic key types to serve different use cases: authentication, signing credentials, encrypting communications, and enabling selective disclosure.

## Supported Key Types

| Algorithm | Curve        | Key Type                            | Primary Use                      |
| --------- | ------------ | ----------------------------------- | -------------------------------- |
| EdDSA     | Ed25519      | `Ed25519VerificationKey2020`        | Authentication, VC signing, IBCT |
| ECDSA     | secp256k1    | `EcdsaSecp256k1VerificationKey2019` | Blockchain-native auth           |
| ECDSA     | P-256        | `JsonWebKey2020`                    | FIDO2 / WebAuthn compatibility   |
| ECDH      | X25519       | `X25519KeyAgreementKey2020`         | DIDComm encryption               |
| BBS+      | BLS12-381 G2 | `Bls12381G2Key2020`                 | Selective disclosure, ZKP        |

***

## Ed25519

Ed25519 is the default and recommended key type for IDA. It provides fast, secure digital signatures based on the Twisted Edwards curve.

### Properties

| Property           | Value            |
| ------------------ | ---------------- |
| Security level     | 128-bit          |
| Public key size    | 32 bytes         |
| Signature size     | 64 bytes         |
| Signing speed      | \~15,000 ops/sec |
| Verification speed | \~7,500 ops/sec  |

### Key Generation (Go)

```go
package main

import (
    "crypto/ed25519"
    "crypto/rand"
    "encoding/hex"
    "fmt"
)

func generateEd25519() {
    pub, priv, err := ed25519.GenerateKey(rand.Reader)
    if err != nil {
        panic(err)
    }

    fmt.Printf("Public key:  %s\n", hex.EncodeToString(pub))
    fmt.Printf("Private key: %s\n", hex.EncodeToString(priv.Seed()))
}
```

### Key Generation (JavaScript)

```javascript
import { generateKeyPair } from '@stablelib/ed25519';
import { encode as base58Encode } from 'bs58';

function generateEd25519() {
  const keyPair = generateKeyPair();
  const publicKeyMultibase = 'z' + base58Encode(
    Buffer.concat([Buffer.from([0xed, 0x01]), keyPair.publicKey])
  );

  return {
    type: 'Ed25519VerificationKey2020',
    publicKeyMultibase,
    privateKey: keyPair.secretKey,
  };
}
```

### Signing and Verification

```go
// Sign a message
message := []byte("Hello, IDA!")
signature := ed25519.Sign(privateKey, message)

// Verify the signature
valid := ed25519.Verify(publicKey, message, signature)
// valid == true
```

### Usage in IDA

* **DID Auth**: Challenge-response authentication
* **VC Proof**: `Ed25519Signature2020` proof suite
* **IBCT Signing**: EdDSA-signed compact JWTs for single-hop delegation

***

## secp256k1

secp256k1 is the elliptic curve used natively by most blockchains (Ethereum, Bitcoin). IDA supports it for blockchain-native operations and compatibility.

### Properties

| Property        | Value                 |
| --------------- | --------------------- |
| Security level  | 128-bit               |
| Public key size | 33 bytes (compressed) |
| Signature size  | 64 bytes (r, s)       |

### Key Generation (Go)

```go
import (
    "crypto/ecdsa"
    "crypto/elliptic"
    "crypto/rand"
    "github.com/ethereum/go-ethereum/crypto"
)

func generateSecp256k1() (*ecdsa.PrivateKey, error) {
    return crypto.GenerateKey()
}
```

### Usage in IDA

* **Blockchain transactions**: Signing ADI blockchain transactions
* **Ethereum compatibility**: Interop with EVM-based systems
* **Address derivation**: Ethereum-style address from public key

***

## X25519 (Key Agreement)

X25519 is a Diffie-Hellman function used for key agreement in DIDComm v2 encrypted messaging.

### Properties

| Property           | Value    |
| ------------------ | -------- |
| Security level     | 128-bit  |
| Public key size    | 32 bytes |
| Shared secret size | 32 bytes |

### Key Agreement Flow

```mermaid
sequenceDiagram
    participant Alice
    participant Bob

    Alice->>Alice: Generate X25519 key pair (skA, pkA)
    Bob->>Bob: Generate X25519 key pair (skB, pkB)
    Alice->>Bob: Send pkA (in DID Document)
    Bob->>Alice: Send pkB (in DID Document)
    Alice->>Alice: sharedSecret = X25519(skA, pkB)
    Bob->>Bob: sharedSecret = X25519(skB, pkA)
    Note over Alice,Bob: Both compute the same shared secret
    Alice->>Bob: Encrypt with XChaCha20-Poly1305(sharedSecret, message)
```

### DIDComm Encryption

```javascript
import { x25519 } from '@stablelib/x25519';
import { XChaCha20Poly1305 } from '@stablelib/xchacha20poly1305';

// Derive shared secret
const sharedSecret = x25519(senderPrivateKey, recipientPublicKey);

// Encrypt message
const aead = new XChaCha20Poly1305(sharedSecret);
const nonce = randomBytes(24);
const ciphertext = aead.seal(nonce, plaintext);
```

***

## BBS+ Signatures

BBS+ is a pairing-based signature scheme on the BLS12-381 curve that enables selective disclosure of signed attributes without revealing the full credential.

### Properties

| Property                 | Value               |
| ------------------------ | ------------------- |
| Security level           | 128-bit             |
| Public key size          | 96 bytes (G2 point) |
| Signature size           | 112 bytes           |
| Selective disclosure     | Yes                 |
| Zero-knowledge proofs    | Yes                 |
| Unlinkable presentations | Yes                 |

### How It Works

```mermaid
graph LR
    subgraph Issuance
        I[Issuer] -->|"Sign all attributes<br />with BBS+"| VC[Signed VC<br />name, age, address, SSN]
    end

    subgraph Presentation
        VC -->|"Selective disclosure"| VP[Verifiable Presentation<br />age only]
    end

    subgraph Verification
        VP -->|"ZK Proof verifies"| V[Verifier<br />confirms age >= 21<br />without seeing name/SSN]
    end
```

1. **Issuance**: Issuer signs all credential attributes as a single BBS+ signature
2. **Derivation**: Holder derives a proof that reveals only selected attributes
3. **Verification**: Verifier confirms the proof without learning hidden attributes

### Selective Disclosure Example

```javascript
import { BBS } from '@mattrglobal/bbs-signatures';

// Issuer: Sign all attributes
const messages = [
  "John Doe",      // attribute 0: name
  "30",            // attribute 1: age
  "123 Main St",   // attribute 2: address
  "999-00-1234"    // attribute 3: SSN
];

const signature = await BBS.sign({
  messages,
  publicKey: issuerBbsPublicKey,
  secretKey: issuerBbsSecretKey,
});

// Holder: Create proof revealing only age (index 1)
const proof = await BBS.createProof({
  signature,
  publicKey: issuerBbsPublicKey,
  messages,
  revealed: [1],  // only reveal attribute at index 1
  nonce: verifierNonce,
});

// Verifier: Verify the proof
const verified = await BBS.verifyProof({
  proof,
  publicKey: issuerBbsPublicKey,
  messages: ["30"],        // only the revealed attribute
  revealed: [1],
  messageCount: 4,         // total attributes in original VC
  nonce: verifierNonce,
});
// verified === true
```

### ZK Predicate Proofs

BBS+ can be combined with ZK circuits to prove predicates:

```
Prove: age >= 21  (without revealing actual age)
Prove: salary >= $50,000  (without revealing exact salary)
Prove: country IN ["US", "CA", "UK"]  (without revealing which one)
```

***

## Zero-Knowledge Identity (zkSync Airbender Compatible)

IDA implements a full ZK Identity system that enables privacy-preserving credential verification on the ADI blockchain. The system is compatible with zkSync Airbender's proving system and zkEVM execution model.

### ZK Proof Architecture

```mermaid
graph LR
    subgraph Off-Chain
        P[Prover] -->|"Generate proof<br />predicates + commitments"| ZKP[ZK Proof<br />Ed25519 signed]
        ZKP -->|"Send proof"| V[Verifier<br />4-stage check]
    end

    subgraph On-Chain ADI
        ZKP -->|"Anchor hash"| SC[ZKProofVerifier<br />bytes32 registry]
        SC -->|"Validity proof"| AB[Airbender<br />zkEVM attestation]
    end
```

### Proof Generation

The ZKP prover generates proofs using Pedersen-like commitments and Schnorr-like responses:

1. **Predicate Evaluation**: Validates that credential values satisfy all predicates (without revealing values)
2. **Commitment Generation**: For each predicate: `C = H(attribute_value || blinding_factor || predicate)`
3. **Response Computation**: For each predicate: `R = H(C || nonce || challenge || blinding_factor)`
4. **Aggregation**: Single proof hash: `A = H(sorted_commitments || sorted_responses || nonce)`
5. **Signing**: Ed25519 signature over `A || challenge || proverDID`

### Supported Predicate Types

| Type             | Description           | Example                     |
| ---------------- | --------------------- | --------------------------- |
| `gt`             | Greater than          | `age > 18`                  |
| `gte`            | Greater than or equal | `age >= 18`                 |
| `lt`             | Less than             | `debt < 10000`              |
| `lte`            | Less than or equal    | `risk <= 5`                 |
| `eq`             | Equality              | `status == 1`               |
| `range`          | Value within bounds   | `650 <= creditScore <= 850` |
| `membership`     | Value in set          | `country in [US, UK, EU]`   |
| `non_membership` | Value not in set      | `country not in [RU, CN]`   |

### Proof Verification (4-Stage)

1. **Structural Integrity**: All required fields present (ID, type, prover DID, predicates, proof data, nonce)
2. **Ed25519 Signature**: Verify prover's signature against public key resolved from DID document
3. **Aggregate Consistency**: Recompute aggregate hash from commitments/responses, compare with proof
4. **Per-Predicate Check**: Each predicate has matching commitment and response entries

### On-Chain Anchoring

Proofs can be anchored on-chain via the `ZKProofVerifier` contract on ADI blockchain:

* Proof hashes are stored as `bytes32` (Poseidon-friendly for Airbender circuits)
* `submitProof()` registers the proof hash with prover DID and credential reference
* `isProofValid()` returns validity status (exists and not revoked)
* `verifyProofOnChain()` marks verification timestamp and emits `ProofVerified` event

### zkSync Airbender Compatibility

The ADI blockchain implements zkSync Airbender standards natively:

* **zkEVM Execution**: Contracts compile with standard Solidity 0.8.24 to zkEVM opcodes
* **Poseidon Hashing**: `bytes32` proof hashes are compatible with Poseidon hash circuits used in Airbender validity proofs
* **State Diff Compression**: Proof registry state changes are compressed in zkSync's state diff model
* **Cross-Chain Verification**: Proof existence on ADI can be verified on L1 via Airbender's validity proof mechanism

### ZK Identity Use Cases

* **Age Verification**: Prove `age >= 18` without revealing birthdate or name
* **KYC/AML**: Prove jurisdictional compliance without storing passport data
* **Proof of Humanity**: Verify uniqueness without biometric exposure (Sybil resistance)
* **Anonymous Governance**: DAO members vote without revealing identity
* **Selective Health Data**: Share vaccination status without full medical record
* **Financial Eligibility**: Prove creditworthiness without exact score disclosure

***

## Key Rotation

Key rotation is critical for long-lived DIDs. IDA supports seamless key rotation:

```mermaid
sequenceDiagram
    participant Controller
    participant IDA API
    participant ADI Chain

    Controller->>Controller: Generate new key pair
    Controller->>IDA API: POST /dids/{did}/keys/rotate
    Note right of Controller: Signed with current auth key
    IDA API->>IDA API: Validate current signature
    IDA API->>IDA API: Add new key to DID Document
    IDA API->>ADI Chain: Update DID Document on-chain
    IDA API->>Controller: Updated DID Document

    Note over Controller,ADI Chain: Old key remains valid for grace period
    Controller->>IDA API: POST /dids/{did}/keys/{old-key-id}/revoke
    IDA API->>ADI Chain: Remove old key from DID Document
```

### Key Rotation Request

```bash
curl -X POST http://localhost:8080/api/v1/dids/did:adi:3f7a.../keys/rotate \
  -H "Authorization: DIDAuth <signed-challenge>" \
  -d '{
    "newKeyType": "Ed25519VerificationKey2020",
    "purpose": ["authentication", "assertionMethod"],
    "revokeOldKey": false
  }'
```

## Algorithm Comparison

| Feature              | Ed25519 | secp256k1 | BBS+ | X25519 |
| -------------------- | ------- | --------- | ---- | ------ |
| Signing              | Yes     | Yes       | Yes  | No     |
| Verification         | Yes     | Yes       | Yes  | No     |
| Key Agreement        | No      | No        | No   | Yes    |
| Selective Disclosure | No      | No        | Yes  | No     |
| ZK Proofs            | No      | No        | Yes  | No     |
| Blockchain Native    | No      | Yes       | No   | No     |
| Speed (sign)         | Fast    | Medium    | Slow | N/A    |
| Quantum Resistant    | No      | No        | No   | No     |