sessionless-1.x-dev/src/KeyStorage/KeyStorage.php

src/KeyStorage/KeyStorage.php
<?php

namespace Drupal\sessionless\KeyStorage;

use Drupal\Core\State\StateInterface;
use ParagonIE\Paserk\Operations\Key\SealingSecretKey;
use ParagonIE\Paseto\Keys\AsymmetricSecretKey;

/**
 * Key Storage
 *
 * @internal
 */
final class KeyStorage implements KeyStorageInterface {

  private const STATE_KEY_FOR_SIGNING_SECRET_KEY = "sessionless.secret_key.signing";
  private const STATE_KEY_FOR_SEALING_SECRET_KEY = "sessionless.secret_key.sealing";
  private const STATE_KEY_FOR_KEY_VERSION = "sessionless.secret_key.version";

  public function __construct(
    protected StateInterface $state,
  ) {}

  public function getSigningSecretKey(): AsymmetricSecretKey {
    $key = $this->state->get(self::STATE_KEY_FOR_SIGNING_SECRET_KEY);
    if (!$key) {
      $key = AsymmetricSecretKey::generate();
      // Prevent key object change on first use.
      $key->assertSecretKeyValid();
      $this->state->set(self::STATE_KEY_FOR_SIGNING_SECRET_KEY, $key);
    }
    return $key;
  }

  public function getSealingSecretKey(): SealingSecretKey {
    $key = $this->state->get(self::STATE_KEY_FOR_SEALING_SECRET_KEY);
    if (!$key) {
      $key = SealingSecretKey::generate();
      // Prevent key object change on first use.
      $key->assertSecretKeyValid();
      $this->state->set(self::STATE_KEY_FOR_SEALING_SECRET_KEY, $key);
    }
    return $key;
  }

  public function dropSecretKeys(): void {
    $this->state->delete(self::STATE_KEY_FOR_SIGNING_SECRET_KEY);
    $this->state->delete(self::STATE_KEY_FOR_SEALING_SECRET_KEY);

    $keyVersion = $this->getKeyVersion();
    $keyVersion++;
    $this->state->set(self::STATE_KEY_FOR_KEY_VERSION, $keyVersion);
  }

  public function getKeyVersion(): int {
    return $this->state->get(self::STATE_KEY_FOR_KEY_VERSION, 1);
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc