Source

timekoin / util / keys.php

Full commit
<?PHP

include '/usr/share/timekoin/public/configuration.php';

global $keys_quiet;
global $keys_cmdline;

$keys_cmdline = ((isset($_GET['cmdline']) && ($_GET['cmdline'] == 1)));
$keys_quiet = ((isset($_GET['quiet']) && ($_GET['quiet'] == 1)));

function println($l) {
  global $keys_cmdline;
  if (!$keys_cmdline) { echo "<br/>"; };
  echo $l;
  if ($keys_cmdline) { echo "\n"; };
}

if(mysql_pconnect(MYSQL_IP,MYSQL_USERNAME,MYSQL_PASSWORD) == FALSE)
{
  println("mySQL connect failed...");
}

if(mysql_select_db(MYSQL_DATABASE) == FALSE)
{
  println("mySQL select database failed...");
}

if ((!isset($_GET['resetkeys'])) || ($_GET['resetkeys'] != 1)) {
  $sql = "SELECT field_data FROM my_keys WHERE field_name = 'server_private_key' LIMIT 1";
  $result = mysql_query($sql);
  if ($result === FALSE) {
    println("Could not access database.");
    exit;
  }
  $result = mysql_result($result,0,"field_data");
  $result = (($result !== "Private Key Goes Here") &&
	     ($result !== ""));
  if ($result) {
    if (!$keys_quiet) { println("A private key is already present."); }
    # A previous key was set
    if ($keys_cmdline) {
      if (!$keys_quiet) { println("Use --reset to force resetting the key."); }
    } else {
      echo "<br/><form method=get><input type=checkbox id=resetkeys name=resetkeys ><label for=resetkeys>Reset private and public keys for Timekoin</label><input type=Submit id=submit name=submit value=\"Reset\"></form>";
    }
    exit;
  }
}

// Create the keypair
$res = openssl_pkey_new(array(
	'private_key_bits' => 1536,
	'private_key_type' => OPENSSL_KEYTYPE_RSA,
));

// Get private key
openssl_pkey_export($res, $privateKey);

// Get public key
$pubKey=openssl_pkey_get_details($res);
$pubKey=$pubKey["key"];

$sql = "UPDATE `my_keys` SET `field_data` = '$privateKey' WHERE `my_keys`.`field_name` = 'server_private_key' LIMIT 1";

	if(mysql_query($sql) == TRUE && empty($privateKey) == FALSE)
	{
	  println("Private Key created and stored in Database");
	}
	else
	{
	  println("Private Key creation failed (OpenSSL Failure)...");
	}

$sql = "UPDATE `my_keys` SET `field_data` = '$pubKey' WHERE `my_keys`.`field_name` = 'server_public_key' LIMIT 1";

	if(mysql_query($sql) == TRUE && empty($pubKey) == FALSE)
	{
	  println("Public Key created and stored in Database");
	}
	else
	{
	  println("Public Key creation failed (OpenSSL Failure)...");
	}	

?>