You are here

public function JwtRsKeyType::validateKeyValue in JSON Web Token Authentication (JWT) 8

Same name and namespace in other branches
  1. 8.0 src/Plugin/KeyType/JwtRsKeyType.php \Drupal\jwt\Plugin\KeyType\JwtRsKeyType::validateKeyValue()

Allows the Key Type plugin to validate the key value.

Parameters

array $form: An associative array containing the structure of the plugin form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the plugin form.

string|null $key_value: The key value to be validated.

Overrides KeyTypeInterface::validateKeyValue

File

src/Plugin/KeyType/JwtRsKeyType.php, line 95

Class

JwtRsKeyType
Defines a key type for JWT RSA Signatures.

Namespace

Drupal\jwt\Plugin\KeyType

Code

public function validateKeyValue(array $form, FormStateInterface $form_state, $key_value) {
  if (!$form_state
    ->getValue('algorithm')) {
    return;
  }

  // Validate the key.
  $algorithm = $form_state
    ->getValue('algorithm');
  if (strpos($key_value, '-----BEGIN PUBLIC KEY-----') !== FALSE) {
    $key_resource = openssl_pkey_get_public($key_value);
  }
  else {
    $key_resource = openssl_pkey_get_private($key_value);
  }
  if ($key_resource === FALSE) {
    $form_state
      ->setErrorByName('key_type', $this
      ->t('Invalid Key.'));
    return;
  }
  $key_details = openssl_pkey_get_details($key_resource);
  if ($key_details === FALSE) {
    $form_state
      ->setErrorByName('key_type', $this
      ->t('Unable to get key details.'));
    return;
  }
  $required_bits = self::getAlgorithmKeysize()[$algorithm];
  if ($key_details['bits'] < $required_bits) {
    $form_state
      ->setErrorByName('key_type', $this
      ->t('Key size (%size bits) is too small for algorithm chosen. Algorithm requires a minimum of %required bits.', [
      '%size' => $key_details['bits'],
      '%required' => $required_bits,
    ]));
  }
  if ($key_details['type'] != OPENSSL_KEYTYPE_RSA) {
    $form_state
      ->setErrorByName('key_type', $this
      ->t('Key must be RSA.'));
  }
  openssl_pkey_free($key_resource);
}