PHP code example of azaharizaman / nexus-crypto

1. Go to this page and download the library: Download azaharizaman/nexus-crypto library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

azaharizaman / nexus-crypto example snippets


use Nexus\Crypto\Services\CryptoManager;
use Nexus\Crypto\Enums\HashAlgorithm;

$crypto = app(CryptoManager::class);

// Hash with default SHA-256
$result = $crypto->hash('sensitive data');
// HashResult(hash: '5d41...', algorithm: SHA256, salt: null)

// Hash with specific algorithm
$result = $crypto->hash('sensitive data', HashAlgorithm::BLAKE2B);

// Verify hash
if ($crypto->verifyHash('sensitive data', $result)) {
    // Data integrity confirmed
}

use Nexus\Crypto\Enums\SymmetricAlgorithm;

// Encrypt with default AES-256-GCM
$encrypted = $crypto->encrypt('confidential information');
// EncryptedData(
//   ciphertext: '8f3a...',
//   iv: '4b2c...',
//   tag: '9d1e...',
//   algorithm: AES256GCM,
//   metadata: []
// )

// Decrypt
$plaintext = $crypto->decrypt($encrypted);

// Encrypt with specific key
$keyId = 'tenant-123-finance';
$encrypted = $crypto->encryptWithKey('payroll data', $keyId);
$plaintext = $crypto->decryptWithKey($encrypted, $keyId);

use Nexus\Crypto\Enums\AsymmetricAlgorithm;

// Generate key pair
$keyPair = $crypto->generateKeyPair(AsymmetricAlgorithm::ED25519);

// Sign data
$signed = $crypto->sign('financial report', $keyPair->privateKey);
// SignedData(
//   data: 'financial report',
//   signature: 'a8f3...',
//   algorithm: ED25519,
//   publicKey: '7b2c...'
// )

// Verify signature
if ($crypto->verifySignature($signed)) {
    // Signature valid - data authentic and unmodified
}

// Generate HMAC signature
$signature = $crypto->hmac($payload, $secret);

// Verify HMAC
if ($crypto->verifyHmac($payload, $signature, $secret)) {
    // Webhook authentic
}

// Manual rotation
$newKey = $crypto->rotateKey('tenant-123-finance');

// Automated rotation (configured in CryptoServiceProvider)
// KeyRotationHandler checks all keys daily and rotates expired ones
// Based on expiresAt field in EncryptionKey value object

final readonly class HashResult
{
    public function __construct(
        public string $hash,              // Hex-encoded hash
        public HashAlgorithm $algorithm,  // Algorithm used
        public ?string $salt = null       // Optional salt (for KDF)
    ) {}
    
    public function toArray(): array;
    public static function fromArray(array $data): self;
}

final readonly class EncryptedData
{
    public function __construct(
        public string $ciphertext,               // Base64-encoded encrypted data
        public string $iv,                       // Initialization vector
        public string $tag,                      // Authentication tag (GCM/Poly1305)
        public SymmetricAlgorithm $algorithm,    // Algorithm used
        public array $metadata = []              // Additional context
    ) {}
    
    public function toArray(): array;
    public static function fromArray(array $data): self;
}

final readonly class SignedData
{
    public function __construct(
        public string $data,                    // Original data
        public string $signature,               // Signature bytes
        public AsymmetricAlgorithm $algorithm,  // Algorithm used
        public ?string $publicKey = null        // Public key (optional)
    ) {}
    
    public function isQuantumResistant(): bool; // Check if PQC algorithm
    public function toArray(): array;
    public static function fromArray(array $data): self;
}

final readonly class KeyPair
{
    public function __construct(
        public string $publicKey,               // Base64-encoded public key
        public string $privateKey,              // Base64-encoded private key
        public AsymmetricAlgorithm $algorithm   // Algorithm used
    ) {}
}

final readonly class EncryptionKey
{
    public function __construct(
        public string $key,                     // Base64-encoded key material
        public SymmetricAlgorithm $algorithm,   // Algorithm
        public DateTimeImmutable $createdAt,
        public ?DateTimeImmutable $expiresAt = null
    ) {}
    
    public function isExpired(ClockInterface $clock): bool;
}

enum HashAlgorithm: string
{
    case SHA256 = 'sha256';
    case SHA384 = 'sha384';
    case SHA512 = 'sha512';
    case BLAKE2B = 'blake2b';
    
    public function isQuantumResistant(): bool;
    public function getSecurityLevel(): int; // Bits (e.g., 256)
}

enum SymmetricAlgorithm: string
{
    case AES256GCM = 'aes-256-gcm';
    case AES256CBC = 'aes-256-cbc';
    case CHACHA20POLY1305 = 'chacha20-poly1305';
    
    public function isAuthenticated(): bool; // GCM/Poly1305 = true
    public function 

enum AsymmetricAlgorithm: string
{
    case HMACSHA256 = 'hmac-sha256';
    case ED25519 = 'ed25519';
    case RSA2048 = 'rsa-2048';
    case RSA4096 = 'rsa-4096';
    case ECDSAP256 = 'ecdsa-p256';
    
    // Phase 2 (stubs for now)
    case DILITHIUM3 = 'dilithium3';
    case KYBER768 = 'kyber768';
    
    public function isQuantumResistant(): bool;
    public function getSecurityLevel(): int;
}

// Recommended defaults (Phase 1)
HashAlgorithm::SHA256           // General hashing
SymmetricAlgorithm::AES256GCM   // Data encryption (authenticated)
AsymmetricAlgorithm::ED25519    // Digital signatures (fast)

// Legacy support
SymmetricAlgorithm::AES256CBC   // Backward compatibility
AsymmetricAlgorithm::RSA2048    // Standards compliance

use Nexus\Crypto\Exceptions\{
    EncryptionException,
    DecryptionException,
    SignatureException,
    InvalidKeyException,
    UnsupportedAlgorithmException,
    FeatureNotImplementedException
};

try {
    $encrypted = $crypto->encrypt($data);
} catch (EncryptionException $e) {
    // Handle encryption failure
    $logger->error('Encryption failed', ['error' => $e->getMessage()]);
}

try {
    $signed = $hybridSigner->sign($data); // Phase 2 feature
} catch (FeatureNotImplementedException $e) {
    // Fall back to classical signing
    $signed = $crypto->sign($data);
}