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

Shh Laravel Package

bentools/shh

Shh! is a lightweight PHP library for handling secrets: generate RSA key pairs, change private key passphrases, encrypt/decrypt payloads, and store encrypted secrets safely so only holders of the private key can decrypt.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require bentools/shh:^1.0
    

    Add to composer.json if using Laravel’s autoloader or ensure vendor/autoload.php is included.

  2. First Use Case: Generate a key pair for encrypting/decrypting secrets:

    use BenTools\Shh\Shh;
    
    [$publicKey, $privateKey] = Shh::generateKeyPair();
    file_put_contents(storage_path('app/public_key.pem'), $publicKey);
    file_put_contents(storage_path('app/private_key.pem'), $privateKey);
    
  3. Encrypt/Decrypt:

    $encrypted = Shh::encrypt('my-secret', $publicKey);
    $decrypted = Shh::decrypt($encrypted, $privateKey);
    

Where to Look First

  • README.md: Focus on the Usage section for core methods (generateKeyPair, encrypt, decrypt).
  • Tests: tests/ directory for edge cases and examples.
  • Config: Check config/shh.php (if using the Symfony bundle) for default settings.

Implementation Patterns

Core Workflows

  1. Key Management:

    • Generate keys once and store securely (e.g., storage/app/keys/).
    • Use environment variables for paths:
      $publicKey = file_get_contents(env('PUBLIC_KEY_PATH'));
      $privateKey = file_get_contents(env('PRIVATE_KEY_PATH'));
      
  2. Encrypting Secrets:

    • Encrypt sensitive data (e.g., API keys, credentials) before storing in the database or config:
      $encryptedDbValue = Shh::encrypt($plaintextSecret, $publicKey);
      // Store $encryptedDbValue in DB/config.
      
  3. Decrypting Secrets:

    • Decrypt during runtime (e.g., in service providers or controllers):
      $secret = Shh::decrypt($encryptedValue, $privateKey);
      config(['services.api.token' => $secret]);
      
  4. Passphrase Protection:

    • Protect private keys with passphrases for added security:
      [$publicKey, $privateKey] = Shh::generateKeyPair('secure-passphrase');
      

Integration Tips

  • Laravel Services: Bind the package to the container for dependency injection:

    $this->app->singleton('shh', function () {
        return new Shh(file_get_contents(storage_path('app/private_key.pem')));
    });
    

    Then inject via constructor:

    public function __construct(private Shh $shh) {}
    
  • Database Encryption: Use Laravel’s Attribute Casting or Accessors to auto-encrypt/decrypt fields:

    use BenTools\Shh\Shh;
    
    protected $casts = [
        'encrypted_secret' => function ($value) {
            return Shh::decrypt($value, $privateKey);
        }
    ];
    
  • Environment Variables: Encrypt secrets in .env files during deployment:

    # Encrypt a value and store in .env
    echo "ENCRYPTED_DB_PASSWORD=$(php artisan shh:encrypt 'my-db-password')" >> .env
    
  • API Responses: Encrypt PII (Personally Identifiable Information) before sending to clients:

    return response()->json(['data' => Shh::encrypt($user->ssn, $publicKey)]);
    

Gotchas and Tips

Pitfalls

  1. Key Rotation:

    • If keys are compromised or rotated, all encrypted data becomes unusable. Plan for key versioning or migration paths.
    • Tip: Store a key_version alongside encrypted data to handle rotations gracefully.
  2. Private Key Exposure:

    • Private keys must never be committed to version control. Use .gitignore and environment-specific storage.
    • Tip: Use Laravel’s env() or .env files for key paths, never hardcode them.
  3. Passphrase Handling:

    • Passphrases must be stored securely (e.g., Laravel Vault, AWS Secrets Manager). Hardcoding them is a security risk.
    • Tip: Prompt users for passphrases at runtime if keys are passphrase-protected.
  4. Algorithm Limitations:

    • Default sha512 with 4096 bits is secure, but custom configurations (e.g., sha256 with 512 bits) may weaken security.
    • Tip: Stick to defaults unless you have a vetted reason to change them.
  5. Performance:

    • RSA operations (especially 4096-bit) can be slow. Avoid encrypting large payloads (e.g., entire files).
    • Tip: Use this for small secrets (e.g., tokens, passwords). For larger data, consider hybrid encryption (e.g., RSA + AES).

Debugging

  1. Invalid Keys:

    • If Shh::decrypt() fails, verify:
      • The private key is correct and not corrupted.
      • The passphrase (if used) matches.
      • The encrypted data wasn’t altered (e.g., base64 corruption).
    • Tip: Log raw key snippets (without exposing full keys) for debugging:
      \Log::debug('Key starts with:', substr($privateKey, 0, 50));
      
  2. Environment Issues:

    • OpenSSL must be installed and enabled in PHP. Check with:
      php -m | grep openssl
      
    • Tip: Use php artisan config:clear if config changes aren’t reflected.
  3. Base64 Encoding:

    • The library returns base64-encoded strings. Ensure your storage/database can handle this format.
    • Tip: Use json_encode() for nested structures before encryption:
      $encrypted = Shh::encrypt(json_encode(['key' => 'value']), $publicKey);
      

Extension Points

  1. Custom Key Storage:

    • Extend the library to fetch keys from cloud storage (e.g., S3) or secret managers:
      class CloudKeyShh extends Shh {
          public function __construct() {
              $privateKey = $this->fetchFromS3('private_key.pem');
              parent::__construct($privateKey);
          }
      }
      
  2. Key Validation:

    • Add validation for key formats or passphrases:
      use BenTools\Shh\Exceptions\InvalidKeyException;
      
      try {
          Shh::decrypt($data, $privateKey);
      } catch (InvalidKeyException $e) {
          // Handle invalid key (e.g., log, retry, or alert).
      }
      
  3. Hybrid Encryption:

    • Combine with AES for better performance with large data:
      $aesKey = Shh::encrypt(openssl_random_pseudo_bytes(32), $publicKey);
      $iv = openssl_random_pseudo_bytes(16);
      $encrypted = openssl_encrypt($data, 'aes-256-cbc', $aesKey, 0, $iv);
      
  4. Laravel Artisan Commands:

    • Create custom commands for key management:
      php artisan shh:generate-keys --passphrase="secure123"
      php artisan shh:encrypt "my-secret" --output=.env
      

Configuration Quirks

  • Default Algorithm: The library defaults to sha512 with 4096 bits. Overriding this requires explicit configuration:

    Shh::generateKeyPair('passphrase', [
        'private_key_bits' => 2048,
        'digest_alg' => 'sha256'
    ]);
    

    Tip: Document custom configurations in your project’s security policy.

  • Key Pair Generation: The generateKeyPair() method returns keys in PEM format. Ensure your storage system supports this format. Tip: Use openssl_pkey_get_details() to inspect key details if needed:

    $keyDetails = openssl_pkey_get_details(openssl_pkey_get_private($privateKey));
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor