Digital Signature — PHP source
Sign messages with Ed25519 or ECDSA and verify signatures. Prove authorship without revealing your private key.
This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
/**
* digital-signature — Ed25519 / ECDSA P-256 message signing and verification.
*
* Language: PHP 7.4+ (bundled ext/openssl + ext/sodium only, both enabled by
* default).
* CosmoDev polyglot showcase port of the `digital-signature` tool, ported from
* src/lib/digital-signature.ts (the canonical TypeScript implementation).
*
* Substitution note: Web Crypto does not exist in PHP, so the algorithms run
* on PHP's bundled crypto extensions — Ed25519 via ext/sodium
* (sodium_crypto_sign_*, deterministic), ECDSA P-256 via ext/openssl
* (random nonce, like WebCrypto). ext/openssl speaks ASN.1 DER signatures, so
* this port converts to/from the 64-byte IEEE P1363 r||s layout the tool
* promises. PHP strings are raw byte buffers, so UTF-8 messages pass through
* byte-exactly with no encode step.
*
* display source — part of CosmoDev's polyglot tool pages.
*/
declare(strict_types=1);
// Fixed DER envelope for Ed25519 keys: SPKI wraps the 32-byte public point,
// PKCS8 wraps the 32-byte seed (RFC 8410). The payloads are constant-shaped.
const DS_ED25519_SPKI_PREFIX = '302a300506032b6570032100';
const DS_ED25519_PKCS8_PREFIX = '302e020100300506032b657004220420';
// OIDs (pre-encoded TLV): 1.2.840.10045.2.1 ecPublicKey, 1.2.840.10045.3.1.7 prime256v1.
const DS_OID_EC = '06072a8648ce3d0201';
const DS_OID_P256 = '06082a8648ce3d030107';
/**
* Generate a fresh signing key pair, exported as hex SPKI / PKCS8 keys.
*
* @return array{public_key: string, private_key: string}
* @throws RuntimeException when key generation fails.
*/
function digital_signature_generate_key_pair(string $algorithm): array
{
digital_signature_assert_algorithm($algorithm);
if ($algorithm === 'ed25519') {
$keypair = sodium_crypto_sign_keypair();
return [
'public_key' => DS_ED25519_SPKI_PREFIX . bin2hex(sodium_crypto_sign_publickey($keypair)),
'private_key' => DS_ED25519_PKCS8_PREFIX
. bin2hex(substr(sodium_crypto_sign_secretkey($keypair), 0, 32)),
];
}
$key = openssl_pkey_new(['curve_name' => 'prime256v1', 'private_key_type' => OPENSSL_KEYTYPE_EC]);
if ($key === false) {
throw new RuntimeException('ECDSA P-256 key generation failed.');
}
$details = openssl_pkey_get_details($key);
if ($details === false || !openssl_pkey_export($key, $sec1Pem)) {
throw new RuntimeException('ECDSA P-256 key generation failed.');
}
// Public PEM is already SPKI; wrap the SEC1 "EC PRIVATE KEY" body in a
// PKCS8 envelope (SEQUENCE { version, algorithm, OCTET STRING }) so both
// halves speak the same DER dialect as Web Crypto.
$spki = ds_pem_body($details['key']);
$sec1 = ds_pem_body($sec1Pem);
$alg = ds_der(0x30, DS_OID_EC . DS_OID_P256);
$pkcs8 = ds_der(0x30, ds_der(0x02, "\x00") . $alg . ds_der(0x04, $sec1));
return ['public_key' => bin2hex($spki), 'private_key' => bin2hex($pkcs8)];
}
/** Sign $message with a hex PKCS8 private key. Returns the hex signature. */
function digital_signature_sign_message(string $message, string $privateKeyHex, string $algorithm): string
{
digital_signature_assert_algorithm($algorithm);
if ($message === '') {
throw new RuntimeException('Message must not be empty.');
}
if ($algorithm === 'ed25519') {
$der = digital_signature_hex_to_bytes($privateKeyHex, 'Private key');
$prefix = hex2bin(DS_ED25519_PKCS8_PREFIX);
if (!str_starts_with($der, $prefix) || strlen($der) !== 48) {
throw new RuntimeException('Invalid private key for Ed25519 (expected hex PKCS8).');
}
$keypair = sodium_crypto_sign_seed_keypair(substr($der, 16));
return bin2hex(sodium_crypto_sign_detached($message, sodium_crypto_sign_secretkey($keypair)));
}
$pem = ds_pem_wrap(digital_signature_hex_to_bytes($privateKeyHex, 'Private key'), 'PRIVATE KEY');
$key = openssl_pkey_get_private($pem);
if ($key === false
|| !openssl_sign($message, $derSig, $key, OPENSSL_ALGO_SHA256)) {
throw new RuntimeException('Invalid private key for ECDSA P-256 (expected hex PKCS8).');
}
return bin2hex(ds_p1363_from_der($derSig));
}
/**
* Verify $signatureHex against $message with a hex SPKI public key.
* Returns false when the signature, message or key simply do not match;
* throws only for malformed input (non-hex / wrong key type).
*/
function digital_signature_verify_signature(string $message, string $signatureHex, string $publicKeyHex, string $algorithm): bool
{
digital_signature_assert_algorithm($algorithm);
$signature = digital_signature_hex_to_bytes($signatureHex, 'Signature');
if ($algorithm === 'ed25519') {
$der = digital_signature_hex_to_bytes($publicKeyHex, 'Public key');
$prefix = hex2bin(DS_ED25519_SPKI_PREFIX);
if (!str_starts_with($der, $prefix) || strlen($der) !== 44) {
throw new RuntimeException('Invalid public key for Ed25519 (expected hex SPKI).');
}
if (strlen($signature) !== 64) {
return false;
}
return sodium_crypto_sign_verify_detached($signature, $message, substr($der, 12));
}
$pem = ds_pem_wrap(digital_signature_hex_to_bytes($publicKeyHex, 'Public key'), 'PUBLIC KEY');
$key = openssl_pkey_get_public($pem);
if ($key === false) {
throw new RuntimeException('Invalid public key for ECDSA P-256 (expected hex SPKI).');
}
return openssl_verify($message, ds_p1363_to_der($signature), $key, OPENSSL_ALGO_SHA256) === 1;
}
/** @internal Throws unless $algorithm is one of the two supported values. */
function digital_signature_assert_algorithm(string $algorithm): void
{
if ($algorithm !== 'ed25519' && $algorithm !== 'ecdsa-p256') {
throw new RuntimeException('Unknown algorithm. Use "ed25519" or "ecdsa-p256".');
}
}
/** @internal Mirrors the TS lib's hexToBytes validation contract. */
function digital_signature_hex_to_bytes(string $hex, string $what): string
{
if ($hex === '' || !preg_match('/^(?:[0-9a-fA-F]{2})+$/', $hex)) {
throw new RuntimeException("{$what} must be a non-empty hex string (pairs of 0-9 / a-f digits).");
}
return hex2bin($hex);
}
/** @internal DER TLV builder (definite, short or long form length). */
function ds_der(int $tag, string $content): string
{
$len = strlen($content);
if ($len < 0x80) {
$lengthBytes = chr($len);
} else {
$body = ltrim(pack('N', $len), "\x00");
$lengthBytes = chr(0x80 | strlen($body)) . $body;
}
return chr($tag) . $lengthBytes . $content;
}
/** @internal Extract the base64 payload of a PEM string as raw DER. */
function ds_pem_body(string $pem): string
{
$lines = preg_split('/\r?\n/', trim($pem));
$body = implode('', array_slice($lines, 1, -1));
$der = base64_decode($body, true);
if ($der === false) {
throw new RuntimeException('Invalid PEM key material.');
}
return $der;
}
/** @internal Wrap raw DER in a PEM armour of the given label. */
function ds_pem_wrap(string $der, string $label): string
{
return "-----BEGIN {$label}-----\n"
. chunk_split(base64_encode($der), 64, "\n")
. "-----END {$label}-----\n";
}
/** @internal ASN.1 DER ECDSA signature (SEQUENCE of two INTEGERs) -> 64-byte P1363 r||s. */
function ds_p1363_from_der(string $der): string
{
$invalid = fn (): RuntimeException => new RuntimeException('OpenSSL returned a malformed ECDSA signature.');
if (strlen($der) < 6 || ord($der[0]) !== 0x30) {
throw $invalid();
}
$int = function (string $der, int $offset) use ($invalid): string {
if (ord($der[$offset]) !== 0x02) {
throw $invalid();
}
$len = ord($der[$offset + 1]);
$value = substr($der, $offset + 2, $len);
return str_pad(ltrim($value, "\x00"), 32, "\x00", STR_PAD_LEFT); // big-endian, left-padded to 32
};
$r = $int($der, 2);
$s = $int($der, 2 + 2 + ord($der[3]));
if (strlen($r) !== 32 || strlen($s) !== 32) {
throw $invalid();
}
return $r . $s;
}
/** @internal 64-byte P1363 r||s -> ASN.1 DER ECDSA signature for OpenSSL. */
function ds_p1363_to_der(string $raw): string
{
if (strlen($raw) !== 64) {
return "\x30\x00"; // structurally invalid input -> empty SEQUENCE -> verify fails
}
$int = function (string $half): string {
$value = ltrim($half, "\x00");
if ($value === '') {
$value = "\x00";
}
if ((ord($value[0]) & 0x80) !== 0) {
$value = "\x00" . $value; // keep the INTEGER positive
}
return chr(0x02) . chr(strlen($value)) . $value;
};
$body = $int(substr($raw, 0, 32)) . $int(substr($raw, 32));
return chr(0x30) . chr(strlen($body)) . $body;
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →