algorithm, self::SUPPORTED_ALGORITHMS, TRUE)) { throw new \InvalidArgumentException(\sprintf('Unsupported DPoP signing algorithm "%s".', $this->algorithm)); } } public static function generate(string $algorithm = 'ES256'): self { $key = match ($algorithm) { 'ES256' => \openssl_pkey_new([ 'private_key_type' => OPENSSL_KEYTYPE_EC, 'curve_name' => 'prime256v1', ]), 'RS256' => \openssl_pkey_new([ 'private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA, ]), default => throw new \InvalidArgumentException(\sprintf('Unsupported DPoP signing algorithm "%s".', $algorithm)), }; $pem = ''; if ($key === FALSE || !\openssl_pkey_export($key, $pem)) { throw new OAuthException('Unable to generate DPoP private key.'); } // OpenSSL writes through a by-reference output parameter. Keep the // defensive runtime check even though Mago retains the initialized type. // @mago-expect analysis:impossible-condition,redundant-type-comparison if (!\is_string($pem)) { throw new OAuthException('Unable to export DPoP private key.'); } return self::fromPem($pem, $algorithm); } public static function fromPem( #[\SensitiveParameter] string $privateKeyPem, string $algorithm = 'ES256', #[\SensitiveParameter] ?string $passphrase = NULL, ): self { if (!\in_array($algorithm, self::SUPPORTED_ALGORITHMS, TRUE)) { throw new \InvalidArgumentException(\sprintf('Unsupported DPoP signing algorithm "%s".', $algorithm)); } return new self(JWKFactory::createFromKey($privateKeyPem, $passphrase, [ 'alg' => $algorithm, 'use' => 'sig', ]), $algorithm); } /** * @param array $values */ public static function fromJwk(#[\SensitiveParameter] array $values, ?string $algorithm = NULL): self { $algorithm ??= \is_string($values['alg'] ?? NULL) ? $values['alg'] : 'ES256'; if (!\in_array($algorithm, self::SUPPORTED_ALGORITHMS, TRUE)) { throw new \InvalidArgumentException(\sprintf('Unsupported DPoP signing algorithm "%s".', $algorithm)); } $values['alg'] = $algorithm; $values['use'] ??= 'sig'; $jwk = JWKFactory::createFromValues($values); if (!$jwk instanceof JWK) { throw new \InvalidArgumentException('DPoP private key must be a single JWK, not a JWK set.'); } return new self($jwk, $algorithm); } /** * @return array */ public function publicJwk(): array { // This assignment carries the PHPDoc refinement for the vendor return type. // @mago-expect lint:inline-variable-return /** @var array $values */ $values = $this->jwk->toPublic()->all(); return $values; } /** * @return array */ public function privateJwk(): array { // This assignment carries the PHPDoc refinement for the vendor return type. // @mago-expect lint:inline-variable-return /** @var array $values */ $values = $this->jwk->all(); return $values; } }