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

Halite Laravel Package

paragonie/halite

High-level, easy-to-use wrapper around libsodium for secure encryption, decryption, and key management in PHP. Provides modern cryptography primitives with safer APIs, supporting authenticated encryption, password hashing, and secure key storage for applications.

Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require paragonie/halite
    

    Halite is a drop-in replacement for PHP’s openssl_* functions, so no additional configuration is needed.

  2. First Use Case: Encrypting a Message

    use ParagonIE\Halite\Halite;
    
    // Generate a new key pair (or load existing)
    $keyPair = Halite::generateKeyPair();
    
    // Encrypt a message
    $encrypted = Halite::encrypt($keyPair->publicKey, 'My secret message');
    
    // Decrypt the message
    $decrypted = Halite::decrypt($keyPair->privateKey, $encrypted);
    
  3. Where to Look First

    • Official Documentation (focus on the "Usage" section).
    • Halite::encrypt(), Halite::decrypt(), and Halite::generateKeyPair() are the core methods.
    • For asymmetric encryption (e.g., public/private keys), use Halite::encrypt($publicKey, $data) and Halite::decrypt($privateKey, $encryptedData).

Implementation Patterns

Common Workflows

  1. Key Management

    • Store private keys securely (e.g., encrypted in a database or environment variables).
    • Use Halite::generateKeyPair() for new keys or Halite::importKeyPair() for existing keys.
    • Example:
      $keyPair = Halite::importKeyPair(
          'private_key_base64',
          'public_key_base64'
      );
      
  2. Symmetric Encryption (Shared Secrets)

    • Use Halite::encrypt($sharedKey, $data) and Halite::decrypt($sharedKey, $encryptedData).
    • Shared keys must be securely exchanged (e.g., via a key exchange protocol like ECDH).
  3. Asymmetric Encryption (Public/Private Keys)

    • Encrypt with a recipient’s public key:
      $encrypted = Halite::encrypt($recipientPublicKey, 'Confidential data');
      
    • Decrypt with the recipient’s private key:
      $decrypted = Halite::decrypt($recipientPrivateKey, $encrypted);
      
  4. Signing and Verification

    • Sign data with a private key:
      $signature = Halite::sign($privateKey, 'Data to sign');
      
    • Verify with a public key:
      $isValid = Halite::verify($publicKey, $signature, 'Data to sign');
      
  5. Integration with Laravel

    • Store keys in .env or a secure vault (e.g., AWS KMS, HashiCorp Vault).
    • Use Laravel’s config() to centralize key paths:
      config(['halite.private_key' => env('HALITE_PRIVATE_KEY')]);
      
    • Create a helper class:
      class CryptoService {
          public function encrypt(string $data): string {
              return Halite::encrypt(
                  config('halite.public_key'),
                  $data
              );
          }
      }
      
  6. Batch Operations

    • Halite supports batch encryption/decryption for multiple messages:
      $encryptedBatch = Halite::encryptBatch($publicKey, ['msg1', 'msg2']);
      $decryptedBatch = Halite::decryptBatch($privateKey, $encryptedBatch);
      

Gotchas and Tips

Pitfalls

  1. Key Exposure

    • Never log or expose private keys. Use environment variables or secure storage.
    • Avoid committing keys to version control (add them to .gitignore).
  2. Key Rotation

    • Rotate keys periodically. Halite does not support key versioning natively; implement a migration strategy (e.g., store old keys temporarily for decryption).
  3. Data Size Limits

    • Libsodium (underlying library) has limits (~2^32 bytes for encrypted data). Avoid encrypting extremely large payloads in a single call.
  4. Time Synchronization for Signatures

    • If using timestamps in signatures, ensure clocks are synchronized between signing and verification parties.
  5. Base64 vs. Raw Keys

    • Halite expects keys in base64-encoded format. Decoding raw binary keys will cause errors.

Debugging

  1. Invalid Key Errors

    • Check key formats with Halite::isValidKeyPair() or Halite::isValidPublicKey().
    • Ensure keys are base64-encoded and properly formatted.
  2. Decryption Failures

    • Verify the correct private key is used (e.g., Halite::decrypt($wrongKey, $data) will fail silently).
    • Check for tampering or corruption in encrypted data.
  3. Performance

    • Asymmetric operations (e.g., RSA) are slower than symmetric. Prefer symmetric encryption for large data.
    • Cache key pairs if reused frequently (but manage memory carefully).

Tips

  1. Use Halite::generateNewKey() for Ephemeral Keys

    • For one-time use cases (e.g., password hashing), generate keys on-the-fly:
      $ephemeralKey = Halite::generateNewKey();
      
  2. Combine with Laravel’s Encryption

    • Use Halite for high-security needs (e.g., PII) and Laravel’s encrypt() for lower-risk data.
  3. Custom Key Storage

    • Extend Halite’s key management by wrapping it in a repository:
      class KeyRepository {
          public function getPrivateKey(): string {
              return cache()->remember('private_key', 3600, fn() => env('HALITE_PRIVATE_KEY'));
          }
      }
      
  4. Error Handling

    • Wrap Halite calls in try-catch blocks to handle exceptions (e.g., Halite\Exception\CryptoException):
      try {
          $decrypted = Halite::decrypt($key, $data);
      } catch (Exception $e) {
          Log::error("Decryption failed: " . $e->getMessage());
          throw new \RuntimeException("Failed to decrypt data.");
      }
      
  5. Testing

    • Use Halite::generateKeyPair() in tests to avoid hardcoding keys:
      public function testEncryption() {
          $keyPair = Halite::generateKeyPair();
          $encrypted = Halite::encrypt($keyPair->publicKey, 'test');
          $this->assertEquals('test', Halite::decrypt($keyPair->privateKey, $encrypted));
      }
      
  6. Libsodium Compatibility

    • Ensure your server has libsodium installed (sudo apt-get install libsodium-dev on Ubuntu). Halite will throw an error if missing.
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport