<?php
if (!extension_loaded('openssl')) {
    fwrite(STDERR, "OpenSSL extension is required.\n");
    exit(1);
}
$bundledConfig = dirname(PHP_BINARY) . DIRECTORY_SEPARATOR . 'extras' . DIRECTORY_SEPARATOR . 'ssl' . DIRECTORY_SEPARATOR . 'openssl.cnf';
if (!getenv('OPENSSL_CONF') && is_file($bundledConfig)) {
    putenv('OPENSSL_CONF=' . $bundledConfig);
}
$key = openssl_pkey_new(array('private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA));
if ($key === FALSE) {
    fwrite(STDERR, "RSA key generation failed; configure OPENSSL_CONF for this PHP runtime.\n");
    while ($message = openssl_error_string()) fwrite(STDERR, $message . PHP_EOL);
    exit(1);
}
openssl_pkey_export($key, $private);
$public = openssl_pkey_get_details($key)['key'];
$payload = rtrim(strtr(base64_encode(json_encode(array(
    'status' => 'active', 'fingerprint_hash' => str_repeat('a', 64)
))), '+/', '-_'), '=');
openssl_sign($payload, $signature, $private, OPENSSL_ALGO_SHA256);
$valid = openssl_verify($payload, $signature, $public, OPENSSL_ALGO_SHA256) === 1;
$tampered = openssl_verify($payload . 'x', $signature, $public, OPENSSL_ALGO_SHA256) === 1;
echo 'rsa_valid=' . ($valid ? 'yes' : 'no') . PHP_EOL;
echo 'tamper_accepted=' . ($tampered ? 'yes' : 'no') . PHP_EOL;
exit($valid && !$tampered ? 0 : 1);
