Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Ecc Laravel Package

mdanter/ecc

Pure-PHP elliptic curve cryptography for ECDSA signatures and Diffie-Hellman key exchange. Supports common NIST and secp curves (including secp256k1), deterministic HMAC-based k generation, and constant-time scalar multiplication. Requires GMP.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require mdanter/ecc
    

    Add to composer.json if using Laravel’s require-dev for testing.

  2. First Use Case: Generate a key pair for ECDSA (e.g., nistp256):

    use mdanter\ecc\EccKey;
    use mdanter\ecc\EccCurve;
    
    $curve = EccCurve::nistp256();
    $key = EccKey::create($curve);
    $privateKey = $key->getPrivate()->toHex();
    $publicKey = $key->getPublic()->toHex();
    
  3. Where to Look First:

    • README for curve support.
    • Source for class structure (EccKey, EccCurve, EccSignature).
    • Tests for usage examples.

Implementation Patterns

Key Generation & Management

  • Curve Selection: Prefer nistp256 or secp256k1 for balance of security and performance.
    $curve = EccCurve::nistp256(); // or EccCurve::secp256k1()
    
  • Key Storage: Serialize private keys securely (e.g., encrypted in DB or environment).
    $key = EccKey::fromHex($privateKeyHex, $curve);
    
  • Key Rotation: Implement a KeyManager service to handle generation, storage, and rotation.

Signing & Verification

  • Signing Data:
    $signature = $key->sign('message_to_sign');
    $signatureHex = $signature->toHex();
    
  • Verification:
    $publicKey = EccKey::fromHex($publicKeyHex, $curve);
    $isValid = $publicKey->verify('message_to_sign', $signature);
    
  • Batch Verification: Use EccSignature::verifyBatch() for multiple signatures (optimization for APIs).

Diffie-Hellman Key Exchange

  • Shared Secret:
    $peerPublicKey = EccKey::fromHex($peerPublicKeyHex, $curve);
    $sharedSecret = $key->getSharedSecret($peerPublicKey);
    
  • Use Case: Securely derive symmetric keys for encryption (e.g., AES).

Integration with Laravel

  • Service Provider:
    // app/Providers/EccServiceProvider.php
    public function register()
    {
        $this->app->singleton('ecc.key', function () {
            return EccKey::create(EccCurve::nistp256());
        });
    }
    
  • Middleware for Auth: Validate ECDSA signatures in API requests.
  • Encryption: Combine with defuse/php-encryption for hybrid encryption.

Gotchas and Tips

Pitfalls

  1. Nonce (k) Reuse:

    • Reusing k in ECDSA breaks security. Use a CSPRNG (e.g., random_bytes()).
    • Fix: Override EccKey::generateNonce() or inject a custom RNG.
      $key->setNonceGenerator(function () {
          return random_bytes(32); // For 256-bit curves
      });
      
  2. Curve Mismatch:

    • Always ensure sender/receiver use the same curve. Serialize the curve name with keys.
    • Debug: Check EccKey::getCurve()->getName() before operations.
  3. Large Key Sizes:

    • nistp521 keys are ~130 chars (hex). Validate storage limits (e.g., DB TEXT fields).
  4. PHP Extensions:

    • Avoid gmp/bcmath for performance-critical apps (this library uses pure PHP).

Debugging

  • Signature Validation:

    • If verify() fails, check:
      • Curve consistency ($key->getCurve()->getName()).
      • Message hash (ECDSA signs hashes, not raw data).
      • Tip: Use hash('sha256', $message) explicitly if needed.
  • Key Import:

    • Invalid hex keys throw EccException. Validate with:
      try {
          EccKey::fromHex($hexKey, $curve);
      } catch (\Exception $e) {
          // Handle error
      }
      

Extension Points

  1. Custom Curves:

    • Extend EccCurve for non-standard curves (rarely needed).
  2. Nonce Customization:

    • Override EccKey::generateNonce() for deterministic nonces (e.g., HKDF-derived).
  3. Serialization:

    • Implement JsonSerializable for API responses:
      $key->jsonSerialize() => ['private' => $privateHex, 'public' => $publicHex, 'curve' => 'nistp256'];
      
  4. Performance:

    • Cache EccCurve instances (they’re immutable).
    • For bulk ops, preload curves:
      $curves = collect(['nistp256', 'secp256k1'])->mapWithKeys(fn ($name) => [
          $name => EccCurve::fromName($name)
      ]);
      

Laravel-Specific Tips

  • Environment Config:
    // config/ecc.php
    return [
        'default_curve' => 'nistp256',
        'key_encryption' => env('ECC_KEY_ENCRYPTION', 'none'),
    ];
    
  • Artisan Commands: Generate keys via CLI:
    // app/Console/Commands/GenerateEccKey.php
    public function handle()
    {
        $key = EccKey::create(EccCurve::nistp256());
        $this->info("Private: {$key->getPrivate()->toHex()}");
    }
    
  • Testing: Use EccKey::fromHex() with known test vectors (e.g., NIST P-256).
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony