PHP code example of tourze / tls-crypto-curves

1. Go to this page and download the library: Download tourze/tls-crypto-curves 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/ */

    

tourze / tls-crypto-curves example snippets




use Tourze\TLSCryptoCurves\NISTP256;

// Create a P-256 curve instance
$curve = new NISTP256();

// Generate a secure key pair
$keyPair = $curve->generateKeyPair();
$privateKey = $keyPair['privateKey']; // PEM format
$publicKey = $keyPair['publicKey'];   // PEM format

// Derive public key from private key
$derivedPublicKey = $curve->derivePublicKey($privateKey);

// Display curve information
echo "Curve Name: " . $curve->getName() . PHP_EOL;
echo "Key Size: " . $curve->getKeySize() . " bits" . PHP_EOL;



use Tourze\TLSCryptoCurves\Curve25519;

// Create a Curve25519 instance
$curve = new Curve25519();

// Generate a key pair for key exchange
$keyPair = $curve->generateKeyPair();
$privateKey = $keyPair['privateKey']; // Binary format
$publicKey = $keyPair['publicKey'];   // Binary format

// Derive public key from private key
$derivedPublicKey = $curve->derivePublicKey($privateKey);

echo "Curve Name: " . $curve->getName() . PHP_EOL;
echo "Key Size: " . $curve->getKeySize() . " bits" . PHP_EOL;



use Tourze\TLSCryptoCurves\NISTP384;
use Tourze\TLSCryptoCurves\NISTP521;
use Tourze\TLSCryptoCurves\Curve448;

// P-384 curve (higher security)
$p384 = new NISTP384();
$keyPair384 = $p384->generateKeyPair();

// P-521 curve (maximum security)
$p521 = new NISTP521();
$keyPair521 = $p521->generateKeyPair();

// Curve448 (modern high-security curve)
$curve448 = new Curve448();
$keyPair448 = $curve448->generateKeyPair();



use Tourze\TLSCryptoCurves\NISTP256;
use Tourze\TLSCryptoCurves\Exception\CurveException;

try {
    $curve = new NISTP256();
    $keyPair = $curve->generateKeyPair();
    
    // Perform cryptographic operations
    $publicKey = $curve->derivePublicKey($keyPair['privateKey']);
    
} catch (CurveException $e) {
    echo "Cryptographic operation failed: " . $e->getMessage() . PHP_EOL;
    // Handle the error appropriately
}

interface CurveInterface
{
    public function getName(): string;
    public function getKeySize(): int;
    public function generateKeyPair(): array;
    public function derivePublicKey(string $privateKey): string;
}