Home > Dev > Crypto > Elliptic Curve Cryptography (ECC) Key Generation and Encryption

Elliptic Curve Cryptography (ECC) Key Generation and Encryption

This code snippet shows how to generate ECC keys and encrypt/decrypt data.

function generate_ecc_keys() {
    $config = array(
        "curve_name" => "prime256v1"
    );
    $res = openssl_pkey_new(array(
        "private_key_type" => OPENSSL_KEYTYPE_EC,
        "curve_name" => "prime256v1"
    ));
    openssl_pkey_export($res, $private_key);
    $public_key = openssl_pkey_get_details($res)["key"];
    return ['private_key' => $private_key, 'public_key' => $public_key];
}

function ecc_encrypt($plaintext, $public_key) {
    openssl_public_encrypt($plaintext, $encrypted, $public_key);
    return base64_encode($encrypted);
}

function ecc_decrypt($ciphertext, $private_key) {
    openssl_private_decrypt(base64_decode($ciphertext), $decrypted, $private_key);
    return $decrypted;
}

// Usage example
$keys = generate_ecc_keys();
$public_key = $keys['public_key'];
$private_key = $keys['private_key'];

$plaintext = 'This is a secret message';
$encrypted = ecc_encrypt($plaintext, $public_key);
$decrypted = ecc_decrypt($encrypted, $private_key);

echo "Public Key: " . $public_key . "\n";
echo "Private Key: " . $private_key . "\n";
echo "Encrypted: " . $encrypted . "\n";
echo "Decrypted: " . $decrypted . "\n";
Back