npm package: @minka/crypto
Description: Cryptographic utilities for Minka Ledger
Latest version: 2.39.0

# Minka Crypto

Cryptographic utilities for the Minka Ledger platform. This library provides a comprehensive set of tools for key management, digital signatures, JWT handling, hashing, and encryption.

## Features

- **Ed25519 Digital Signatures** - Sign and verify data using EdDSA (Ed25519)
- **JWT Support** - Create and verify JSON Web Tokens with EdDSA algorithm
- **Deterministic Hashing** - SHA-256 hashing with RFC 8785 compliant serialization
- **Key Management** - Generate, encrypt, and decrypt cryptographic keys
- **Cross-Platform** - Works in both Node.js and browser environments
- **Hashicorp Vault Compatible** - Interoperable with Vault-generated Ed25519 keys

## Installation

```bash
npm install @minka/crypto
```

## Quick Start

```typescript
import { createKeyPair, createHash, signHash, verifySignature, signJWT, verifyJWT } from '@minka/crypto'

// Generate a new Ed25519 key pair
const keyPair = await createKeyPair()
// { format: 'ed25519-raw', public: '...', secret: '...' }

// Hash some data
const hash = createHash({ handle: 'my-record', amount: 100 })

// Sign the hash
const signature = await signHash(hash, keyPair)

// Verify the signature
const isValid = await verifySignature(hash, signature)
```

## API Reference

### Key Management

#### `createKeyPair()`

Creates a new Ed25519 key pair for signing.

```typescript
const keyPair = await createKeyPair()
// Returns: { format: 'ed25519-raw', public: string, secret: string }
```

#### `encryptSecretKey(secret, password)`

Encrypts an Ed25519 secret key using PKCS5/PBES2 with:

- PBKDF2 key derivation with SHA-256
- AES-256-CBC encryption

```typescript
const encryptedSecret = await encryptSecretKey(keyPair.secret, 'my-password')
```

#### `decryptSecretKey(encryptedSecret, password)`

Decrypts an Ed25519 secret key encrypted with `encryptSecretKey`.

```typescript
const secret = await decryptSecretKey(encryptedSecret, 'my-password')
```

#### `isSecretKeyEncrypted(secret)`

Checks if a secret key is PKCS5 encrypted.

```typescript
const isEncrypted = isSecretKeyEncrypted(secret)
// Returns: boolean
```

#### `encryptWithPassword(data, password)` (Node.js only)

Encrypts any string with a password using AES-256-CBC.

```typescript
const { packed, unpacked } = await encryptWithPassword('sensitive data', 'password')
// packed: JSON string for storage/transport
// unpacked: EncryptedString object
```

#### `decryptWithPassword(encrypted, password)` (Node.js only)

Decrypts data encrypted with `encryptWithPassword`.

```typescript
const data = await decryptWithPassword(packed, 'password')
```

### Digital Signatures

#### `signHash(dataHash, keyPair, customData?)`

Signs a hash using Ed25519.

```typescript
const signature = await signHash(hash, keyPair, {
  status: 'approved',
  timestamp: Date.now(),
})
// Returns: LedgerProof object with method, public, result, digest, and optional custom
```

#### `verifySignature(dataHash, signature)`

Verifies an Ed25519 signature.

```typescript
const isValid = await verifySignature(hash, signature)
// Returns: boolean
```

### Hashing

#### `createHash(data)`

Creates a SHA-256 hash of the provided data using deterministic JSON serialization (RFC 8785).

```typescript
const hash = createHash({
  handle: 'test',
  claims: [{ action: 'transfer', amount: 100 }],
})
// Returns: hex-encoded SHA-256 hash
```

#### `createSignatureDigest(dataHash, customData?)`

Creates a signature digest that includes both the data hash and optional custom data.

```typescript
const digest = createSignatureDigest(hash, { status: 'prepared' })
```

### JWT (JSON Web Tokens)

#### `signJWT(payload, secret, kid?)`

Signs a JWT using EdDSA (Ed25519).

```typescript
const jwt = await signJWT(
  {
    iss: 'my-app',
    sub: keyPair.public,
    aud: 'api',
    iat: Math.floor(Date.now() / 1000),
    exp: Math.floor(Date.now() / 1000) + 3600,
  },
  keyPair.secret,
  keyPair.public, // optional kid (key id)
)
```

#### `verifyJWT(jwt, publicKey, format?)`

Verifies a JWT signature. Supports EdDSA (Ed25519) and RS256.

```typescript
const result = await verifyJWT(jwt, keyPair.public)
// Returns: { payload, protectedHeader }
```

#### `decodeJWT(jwt)`

Decodes a JWT without verification.

```typescript
const payload = decodeJWT(jwt)
// Returns: { iss, sub, aud, iat, exp, jti?, hsh? }
```

#### `getJWTProtectedHeader(jwt)`

Extracts the protected header from a JWT.

```typescript
const header = getJWTProtectedHeader(jwt)
// Returns: { alg, kid }
```

### Key Format Utilities

#### `importPublicKey(key, format?)` / `exportPublicKey(key)`

Import/export Ed25519 public keys between raw (base64) and DER formats.

#### `importPrivateKey(key)` / `exportPrivateKey(key)`

Import/export Ed25519 private keys between raw (base64) and DER formats.

### Assertions

#### `assertSignatureMethod(method)`

Validates that the signature method is `ed25519-v2`.

#### `assertKeyFormat(format)`

Validates that the key format is `ed25519-raw`.

## Key Formats

| Format        | Description     | Length (base64) |
| ------------- | --------------- | --------------- |
| `ed25519-raw` | Raw Ed25519 key | 44 characters   |

## Cryptographic Standards

This library implements the following standards:

- **Ed25519** - Edwards-curve Digital Signature Algorithm (RFC 8032)
- **EdDSA** - Edwards-curve Digital Signature Algorithm for JWT (RFC 8037)
- **PKCS#5 / PBES2** - Password-Based Encryption Scheme 2 (RFC 2898)
- **AES-256-CBC** - Advanced Encryption Standard with Cipher Block Chaining (for key encryption)
- **SHA-256** - Secure Hash Algorithm (FIPS 180-4)
- **RFC 8785** - JSON Canonicalization Scheme (JCS) for deterministic serialization

## Platform Support

| Feature               | Node.js | Browser |
| --------------------- | ------- | ------- |
| Key pair generation   | Yes     | Yes     |
| Signing/verification  | Yes     | Yes     |
| JWT sign/verify       | Yes     | Yes     |
| Hashing               | Yes     | Yes     |
| Secret key encryption | Yes     | Yes     |
| Password encryption   | Yes     | No      |

## Hashicorp Vault Compatibility

This library is compatible with Ed25519 keys generated by Hashicorp Vault's Transit secrets engine:

1. Keys must be created with `type=ed25519` and `derived=false`
2. Public keys can be exported directly from Vault (raw, 44 characters base64)
3. Signatures created by Vault can be verified using `verifySignature()`
4. Hashes should be pre-computed before signing with Vault

## Security Considerations

- **Never expose secret keys** - Store encrypted or use a secrets manager
- **Rotate keys regularly** - Implement key rotation policies
- **Validate inputs** - Always validate signatures before trusting data

## License

MIT