Home > Dev > Crypto > Digital Signatures

Digital Signatures

This code snippet demonstrates how to create and verify digital signatures using RSA keys.

function sign_data($data, $private_key) {
    openssl_sign($data, $signature, $private_key, OPENSSL_ALGO_SHA256);
    return base64_encode($signature);
}

function verify_signature($data, $signature, $public_key) {
    $signature = base64_decode($signature);
    return openssl_verify($data, $signature, $public_key, OPENSSL_ALGO_SHA256) === 1;
}

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

$data = 'This is some data to sign';
$signature = sign_data($data, $private_key);
$is_valid = verify_signature($data, $signature, $public_key);

echo "Signature: " . $signature . "\n";
echo "Is Valid: " . ($is_valid ? 'Yes' : 'No') . "\n";
Back