You are here

function oauth2_server_generate_keys in OAuth2 Server 7

Generates a pair of private and public keys using OpenSSL.

The public key is stored in a PEM encoded X.509 certificate, following Google's example. The certificate can be passed to openssl_verify() directly.

Return value

array An array with the following keys:

  • private_key: The generated private key.
  • public_key: The generated public key certificate (PEM encoded X.509).
2 calls to oauth2_server_generate_keys()
oauth2_server_cron in ./oauth2_server.module
Implements hook_cron().
oauth2_server_get_keys in ./oauth2_server.module
Returns the pair of private and public keys used to sign tokens.

File

./oauth2_server.module, line 820
Provides OAuth2 server functionality.

Code

function oauth2_server_generate_keys() {
  $module_path = drupal_get_path('module', 'oauth2_server');
  $config = array(
    'config' => $module_path . '/oauth2_server.openssl.cnf',
  );

  // Generate a private key.
  $resource = openssl_pkey_new($config);
  openssl_pkey_export($resource, $private_key);

  // Generate a public key certificate valid for 2 days.
  $serial = variable_get('oauth2_server_next_certificate_id', 0);
  $dn = array(
    'CN' => url(NULL, array(
      'absolute' => TRUE,
    )),
  );
  $csr = openssl_csr_new($dn, $resource, $config);
  $x509 = openssl_csr_sign($csr, NULL, $resource, 2, $config, $serial);
  openssl_x509_export($x509, $public_key_certificate);

  // Increment the id for next time. db_next_id() is not used since it can't
  // guarantee sequential numbers.
  variable_set('oauth2_server_next_certificate_id', ++$serial);
  return array(
    'private_key' => $private_key,
    'public_key' => $public_key_certificate,
  );
}