VOOZH about

URL: https://deepwiki.com/hypervel/encryption/4.1-encryption-contracts-and-interfaces

⇱ Encryption Contracts and Interfaces | hypervel/encryption | DeepWiki


Loading...
Menu

Encryption Contracts and Interfaces

Purpose and Scope

This document describes the contract layer of the hypervel/encryption package, which defines the behavioral contracts that all encryption implementations must fulfill. The two primary interfaces—Encrypter and StringEncrypter—establish the public API for encryption operations, key management, and data serialization.

For information about the concrete implementation of these contracts, see The Encrypter Implementation. For details on the exceptions thrown by these methods, see Error Handling and Exceptions.


Contract Architecture Overview

The encryption system uses interface-based design to separate contract definition from implementation. This allows for dependency injection, testing with mock implementations, and potential future implementations with different cryptographic backends.

Contract Layer Structure


Sources: src/Contracts/Encrypter.php1-38 src/Contracts/StringEncrypter.php1-23


The Encrypter Interface

The Encrypter interface defines the core contract for encryption implementations. It is located at src/Contracts/Encrypter.php7-37 and provides five methods covering encryption operations and key management.

Interface Definition

MethodParametersReturn TypeExceptionsDescription
encrypt()mixed $value
bool $serialize = true
stringEncryptExceptionEncrypts any PHP value, optionally serializing it first
decrypt()string $payload
bool $unserialize = true
mixedDecryptExceptionDecrypts a payload, optionally unserializing the result
getKey()NonestringNoneReturns the current encryption key
getAllKeys()NonearrayNoneReturns current key plus all previous keys
getPreviousKeys()NonearrayNoneReturns only the previous encryption keys

Sources: src/Contracts/Encrypter.php9-36

Encryption and Decryption Methods

The encrypt() and decrypt() methods form the core cryptographic operations:


Sources: src/Contracts/Encrypter.php9-21

Method: encrypt()

Defined at src/Contracts/Encrypter.php14 this method encrypts a value and returns a base64-encoded string containing the encrypted payload.

Parameters:

  • mixed $value: Any PHP value to encrypt (string, array, object, etc.)
  • bool $serialize: Whether to serialize the value before encryption (default: true)

Return Value: A base64-encoded string containing a JSON structure with cryptographic artifacts (IV, ciphertext, MAC/tag).

Exceptions: Throws \Hypervel\Encryption\Exceptions\EncryptException if encryption fails.

Serialization Behavior: When $serialize is true, the value is serialized using PHP's serialize() function before encryption. This allows encryption of complex data structures. When false, the value must be a string.

Method: decrypt()

Defined at src/Contracts/Encrypter.php21 this method decrypts a payload previously encrypted with encrypt().

Parameters:

  • string $payload: The base64-encoded encrypted payload
  • bool $unserialize: Whether to unserialize the decrypted value (default: true)

Return Value: The decrypted value. Type depends on what was originally encrypted and the $unserialize parameter.

Exceptions: Throws \Hypervel\Encryption\Exceptions\DecryptException if:

  • The payload is malformed
  • MAC/tag validation fails
  • Decryption fails with all available keys
  • The payload structure is invalid

Deserialization Behavior: When $unserialize is true, the implementation calls unserialize() on the decrypted data. When false, raw decrypted bytes are returned as a string.

Sources: src/Contracts/Encrypter.php14-21

Key Management Methods

The interface defines three methods for accessing encryption keys, supporting key rotation scenarios:


Sources: src/Contracts/Encrypter.php23-36

Method: getKey()

Defined at src/Contracts/Encrypter.php26 returns the current encryption key as a raw byte string.

Parameters: None

Return Value: string - The current encryption key (raw bytes, not base64-encoded)

Usage: This key is used for all encryption operations. During decryption, it is the first key attempted.

Method: getAllKeys()

Defined at src/Contracts/Encrypter.php31 returns an array containing the current key followed by all previous keys.

Parameters: None

Return Value: array - Array of key strings, with current key at index 0

Usage: Used during decryption to attempt decryption with multiple keys, enabling zero-downtime key rotation.

Method: getPreviousKeys()

Defined at src/Contracts/Encrypter.php36 returns only the previous encryption keys, excluding the current key.

Parameters: None

Return Value: array - Array of previous key strings

Usage: Useful for auditing, key management tools, and determining if old keys can be retired.

Sources: src/Contracts/Encrypter.php23-36


The StringEncrypter Interface

The StringEncrypter interface provides specialized methods for encrypting strings without serialization overhead. It is defined at src/Contracts/StringEncrypter.php7-22 as a separate contract that can be implemented alongside or independently of the Encrypter interface.

Interface Definition

MethodParametersReturn TypeExceptionsDescription
encryptString()string $valuestringEncryptExceptionEncrypts a string without serialization
decryptString()string $payloadstringDecryptExceptionDecrypts a string without deserialization

Sources: src/Contracts/StringEncrypter.php9-21

String-Specific Operations


Sources: src/Contracts/StringEncrypter.php1-23

Method: encryptString()

Defined at src/Contracts/StringEncrypter.php14 this method encrypts a string value without applying PHP serialization.

Parameters:

  • string $value: The string to encrypt

Return Value: string - Base64-encoded encrypted payload

Exceptions: Throws \Hypervel\Encryption\Exceptions\EncryptException if encryption fails.

Relationship to encrypt(): This method is functionally equivalent to calling encrypt($value, false) where $value is a string. It provides a more explicit, type-safe API for string-only operations.

Method: decryptString()

Defined at src/Contracts/StringEncrypter.php21 this method decrypts a payload and returns the raw string without deserialization.

Parameters:

  • string $payload: The base64-encoded encrypted payload

Return Value: string - The decrypted string value

Exceptions: Throws \Hypervel\Encryption\Exceptions\DecryptException if decryption or validation fails.

Relationship to decrypt(): This method is functionally equivalent to calling decrypt($payload, false) and expecting a string result. It provides stronger type guarantees in the method signature.

Sources: src/Contracts/StringEncrypter.php9-21


Interface Relationship and Implementation Contract

The standard implementation pattern is for a single class to implement both interfaces, providing a unified encryption service that supports both serialized and non-serialized operations.

Implementation Contract


Sources: src/Contracts/Encrypter.php1-38 src/Contracts/StringEncrypter.php1-23

Why Two Separate Interfaces?

The separation of Encrypter and StringEncrypter into distinct interfaces serves several architectural purposes:

ReasonBenefit
Interface SegregationClients that only need string encryption can depend on a narrower contract
Type SafetyencryptString() and decryptString() have stricter type signatures than their generic counterparts
API ClarityMethod names explicitly indicate that serialization is not performed
Backward CompatibilityAllows gradual migration from generic methods to specialized methods
TestingEnables creation of mock implementations that only support string operations

Sources: src/Contracts/Encrypter.php1-38 src/Contracts/StringEncrypter.php1-23


Type Hinting and Dependency Injection

When using these interfaces in application code, type hint against the appropriate interface based on your requirements:

Type Hinting Examples


Type Hinting Guidelines:

  1. Type hint Encrypter when you need:

    • Key management operations (getKey(), getAllKeys(), getPreviousKeys())
    • Encryption of complex data structures (arrays, objects)
    • Maximum flexibility in what can be encrypted
  2. Type hint StringEncrypter when you need:

    • Only string encryption/decryption
    • Explicit guarantee that no serialization occurs
    • A narrower, more focused API surface
  3. Type hint both (intersection type) if your code requires both capabilities and you want compile-time verification that the implementation provides both.

Sources: src/Contracts/Encrypter.php1-38 src/Contracts/StringEncrypter.php1-23


Contract Guarantees and Invariants

Implementations of these interfaces must maintain the following guarantees:

Operational Invariants

InvariantDescription
Roundtrip Integritydecrypt(encrypt($value, $s), $s) === $value for any value and serialize flag
Key ConsistencygetKey() returns the same value throughout the object's lifetime unless explicitly changed
Key OrderinggetAllKeys()[0] always equals getKey()
Previous Keys SubsetAll keys in getPreviousKeys() appear in getAllKeys() starting from index 1
Deterministic FailuresSame malformed payload always throws the same exception type
FreshnessEach encrypt() call generates a new, random IV

Exception Guarantees


Contract Requirements:

  • Implementations must throw EncryptException for any encryption failure
  • Implementations must throw DecryptException for any decryption failure
  • Exceptions must extend RuntimeException
  • Exceptions must not leak sensitive key material in messages

Sources: src/Contracts/Encrypter.php9-21 src/Contracts/StringEncrypter.php9-21


Summary

The contract layer consists of two interfaces that together define the complete encryption API:

Both interfaces are typically implemented by a single class that provides unified encryption services. The separation enables interface segregation while the common implementation ensures consistency.

For details on how these contracts are implemented, see The Encrypter Implementation. For information on how encrypter instances are created and configured, see The Encrypter Factory.