You are here

public static function OAuthKey::generate in Lightning API 8

Same name and namespace in other branches
  1. 8.4 src/OAuthKey.php \Drupal\lightning_api\OAuthKey::generate()
  2. 8.2 src/OAuthKey.php \Drupal\lightning_api\OAuthKey::generate()
  3. 8.3 src/OAuthKey.php \Drupal\lightning_api\OAuthKey::generate()

Generates an asymmetric key pair for OAuth authentication.

Parameters

array $options: (optional) Additional configuration to pass to OpenSSL functions.

Return value

string[] Returns the private and public key components, in that order.

Throws

\Drupal\lightning_api\Exception\KeyGenerationException If an error occurs during key generation or storage.

1 call to OAuthKey::generate()
OAuthKeyForm::submitForm in src/Form/OAuthKeyForm.php
Form submission handler.

File

src/OAuthKey.php, line 115

Class

OAuthKey

Namespace

Drupal\lightning_api

Code

public static function generate(array $options = []) {
  if (extension_loaded('openssl') == FALSE) {
    throw new KeyGenerationException('The OpenSSL PHP extension is unavailable');
  }
  $options += [
    'private_key_bits' => 2048,
    'private_key_type' => OPENSSL_KEYTYPE_RSA,
  ];
  $key_pair = [
    NULL,
  ];
  $pk = openssl_pkey_new($options);
  if (empty($pk)) {
    throw new KeyGenerationException();
  }

  // Get the private key as a string.
  $victory = openssl_pkey_export($pk, $key_pair[0], NULL, $options);
  if (empty($victory)) {
    throw new KeyGenerationException();
  }

  // Get the public key as a string.
  $key = openssl_pkey_get_details($pk)['key'];
  if (empty($key)) {
    throw new KeyGenerationException();
  }
  array_push($key_pair, $key);
  openssl_pkey_free($pk);
  return $key_pair;
}