Phase 0: Fundament für Inhaus
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m14s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m12s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 1m7s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 1m19s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 1m32s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 1m22s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 1m32s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 1m35s
CI / Build-Artefakte aktuell (pull_request) Failing after 1m7s

- Laravel 13 mit Filament 5 (Admin), Inertia 3 + Vue 3 + Vuetify 4 (Material 3)
- Anmeldung über Fortify (Login, Passwort vergessen/ändern), keine Selbstregistrierung
- Profil mit Profilbild (WebP in festen Größen), Personenseiten, Header mit Avatar-Menü
- Material-3-Farbschema aus der Primärfarbe, hell/dunkel/System pro Person
- Basis-Branding (Portalname, Logo, Primärfarbe) im Admin unter „Erscheinungsbild“
- Benutzerverwaltung im Admin, Zugang vorläufig über is_admin
- vendor/ (ohne Dev-Pakete) und Frontend-Build mitversioniert, Dev-Pakete in vendor-dev/
- PHPUnit-Tests gegen MySQL/MariaDB, Forgejo-CI-Matrix, Docker-Entwicklungsumgebung
- VERSION, CHANGELOG.md und CONTRIBUTING.md mit Release-Ablauf

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-25 20:35:30 +00:00
parent 7197eaebf2
commit 9c0f8de791
15771 changed files with 1564103 additions and 5 deletions

View file

@ -0,0 +1,282 @@
<?php
declare(strict_types=1);
namespace Cose\Key;
use function array_key_exists;
use function in_array;
use InvalidArgumentException;
use function is_int;
use function is_string;
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
use SpomkyLabs\Pki\ASN1\Type\Primitive\BitString;
use SpomkyLabs\Pki\ASN1\Type\Primitive\Integer;
use SpomkyLabs\Pki\ASN1\Type\Primitive\ObjectIdentifier;
use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
use SpomkyLabs\Pki\ASN1\Type\Tagged\ExplicitlyTaggedType;
use function sprintf;
use function strlen;
/**
* @final
* @see \Cose\Tests\Key\Ec2KeyTest
*/
class Ec2Key extends Key
{
final public const CURVE_P256 = 1;
final public const CURVE_P256K = 8;
final public const CURVE_P384 = 2;
final public const CURVE_P521 = 3;
final public const CURVE_NAME_P256 = 'P-256';
/**
* The registered name of COSE curve 8 (RFC 8812, sections 3.1 and 4.2) and the name OpenSSL gives it.
*/
final public const CURVE_NAME_SECP256K1 = 'secp256k1';
/**
* @deprecated The draft-era spelling of curve 8, from draft-ietf-cose-webauthn-algorithms-00, renamed to
* "secp256k1" before -01 and never registered. Still accepted; use CURVE_NAME_SECP256K1 instead.
*/
final public const CURVE_NAME_P256K = 'P-256K';
final public const CURVE_NAME_P384 = 'P-384';
final public const CURVE_NAME_P521 = 'P-521';
final public const CURVE_BP256 = 256;
final public const CURVE_BP320 = 257;
final public const CURVE_BP384 = 258;
final public const CURVE_BP512 = 259;
final public const CURVE_NAME_BP256 = 'brainpoolP256r1';
final public const CURVE_NAME_BP320 = 'brainpoolP320r1';
final public const CURVE_NAME_BP384 = 'brainpoolP384r1';
final public const CURVE_NAME_BP512 = 'brainpoolP512r1';
final public const DATA_CURVE = -1;
final public const DATA_X = -2;
final public const DATA_Y = -3;
final public const DATA_D = -4;
private const SUPPORTED_CURVES_INT = [
self::CURVE_P256,
self::CURVE_P256K,
self::CURVE_P384,
self::CURVE_P521,
self::CURVE_BP256,
self::CURVE_BP320,
self::CURVE_BP384,
self::CURVE_BP512,
];
/**
* RFC 9053, section 7.1, table 19 types "crv" as "int / tstr": a curve may be named instead of numbered. Each of
* these names maps to the identifier of the "COSE Elliptic Curves" registry that curveId() exposes.
*
* @var array<string, int>
*/
private const CURVE_NAME_TO_ID = [
self::CURVE_NAME_P256 => self::CURVE_P256,
self::CURVE_NAME_SECP256K1 => self::CURVE_P256K,
// The deprecated alias is listed on purpose: it is what keeps the draft-era name working.
// @phpstan-ignore classConstant.deprecated
self::CURVE_NAME_P256K => self::CURVE_P256K,
self::CURVE_NAME_P384 => self::CURVE_P384,
self::CURVE_NAME_P521 => self::CURVE_P521,
self::CURVE_NAME_BP256 => self::CURVE_BP256,
self::CURVE_NAME_BP320 => self::CURVE_BP320,
self::CURVE_NAME_BP384 => self::CURVE_BP384,
self::CURVE_NAME_BP512 => self::CURVE_BP512,
];
private const NAMED_CURVE_OID = [
self::CURVE_P256 => '1.2.840.10045.3.1.7',
// NIST P-256 / secp256r1
self::CURVE_P256K => '1.3.132.0.10',
// SECG secp256k1 (RFC 8812)
self::CURVE_P384 => '1.3.132.0.34',
// NIST P-384 / secp384r1
self::CURVE_P521 => '1.3.132.0.35',
// NIST P-521 / secp521r1
self::CURVE_BP256 => '1.3.36.3.3.2.8.1.1.7',
// brainpoolP256r1
self::CURVE_BP320 => '1.3.36.3.3.2.8.1.1.9',
// brainpoolP320r1
self::CURVE_BP384 => '1.3.36.3.3.2.8.1.1.11',
// brainpoolP384r1
self::CURVE_BP512 => '1.3.36.3.3.2.8.1.1.13',
// brainpoolP512r1
];
private const CURVE_KEY_LENGTH = [
self::CURVE_P256 => 32,
self::CURVE_P256K => 32,
self::CURVE_P384 => 48,
self::CURVE_P521 => 66,
self::CURVE_BP256 => 32,
self::CURVE_BP320 => 40,
self::CURVE_BP384 => 48,
self::CURVE_BP512 => 64,
];
/**
* @param array<int|string, mixed> $data
*/
public function __construct(array $data)
{
// Everything below is read from attacker-supplied CBOR: each entry is checked to be present and of the
// expected PHP type before it is used, so that a malformed key always leaves through the
// InvalidArgumentException this library documents rather than through a warning, a TypeError or an Error.
$data = self::normalizeIntegerEntries($data, self::DATA_CURVE, self::TYPE);
parent::__construct($data);
if ($data[self::TYPE] !== self::TYPE_EC2 && $data[self::TYPE] !== self::TYPE_NAME_EC2) {
throw new InvalidArgumentException('Invalid EC2 key. The key type does not correspond to an EC2 key');
}
// RFC 9053 section 7.1.1: "For public keys, it is REQUIRED that 'crv', 'x', and 'y' be present".
if (! isset($data[self::DATA_CURVE], $data[self::DATA_X], $data[self::DATA_Y])) {
throw new InvalidArgumentException('Invalid EC2 key. The curve or the "x/y" coordinates are missing');
}
// The curve is checked first: the coordinate lengths below are read from a table indexed by the curve.
$curveId = self::toCurveId($data[self::DATA_CURVE]);
if ($curveId === null) {
throw new InvalidArgumentException('The curve is not supported');
}
$length = self::CURVE_KEY_LENGTH[$curveId];
// RFC 9053 section 7.1, table 19 types "x", "y" and "d" as byte strings.
foreach ([
self::DATA_X => 'x',
self::DATA_Y => 'y',
] as $index => $name) {
if (! is_string($data[$index])) {
throw new InvalidArgumentException(sprintf('Invalid type for %s coordinate', $name));
}
if (strlen($data[$index]) !== $length) {
throw new InvalidArgumentException(sprintf('Invalid length for %s coordinate', $name));
}
}
// RFC 5915 section 3: the private key is "an octet string of length ceiling (log2(n)/8)".
if (array_key_exists(self::DATA_D, $data)
&& (! is_string($data[self::DATA_D]) || strlen($data[self::DATA_D]) !== $length)) {
throw new InvalidArgumentException('Invalid length for d');
}
}
/**
* @param array<int|string, mixed> $data
*/
public static function create(array $data): self
{
return new self($data);
}
public function toPublic(): self
{
$data = $this->getData();
unset($data[self::DATA_D]);
return new self($data);
}
public function x(): string
{
return $this->get(self::DATA_X);
}
public function y(): string
{
return $this->get(self::DATA_Y);
}
public function isPrivate(): bool
{
return array_key_exists(self::DATA_D, $this->getData());
}
public function d(): string
{
if (! $this->isPrivate()) {
throw new InvalidArgumentException('The key is not private.');
}
return $this->get(self::DATA_D);
}
/**
* The curve as the key carries it, which RFC 9053 section 7.1 allows to be either the identifier of the "COSE
* Elliptic Curves" registry or a name. Use curveId() to get the identifier whatever form was supplied.
*/
public function curve(): int|string
{
return $this->get(self::DATA_CURVE);
}
/**
* The value of the curve in the IANA "COSE Elliptic Curves" registry, whichever of the two forms the key uses.
*/
public function curveId(): int
{
$curve = $this->curve();
return is_int($curve) ? $curve : self::CURVE_NAME_TO_ID[$curve];
}
public function asPEM(): string
{
if ($this->isPrivate()) {
$der = Sequence::create(
Integer::create(1),
OctetString::create($this->d()),
ExplicitlyTaggedType::create(0, ObjectIdentifier::create($this->getCurveOid())),
ExplicitlyTaggedType::create(1, BitString::create($this->getUncompressedCoordinates())),
);
return $this->pem('EC PRIVATE KEY', $der->toDER());
}
$der = Sequence::create(
Sequence::create(
ObjectIdentifier::create('1.2.840.10045.2.1'),
ObjectIdentifier::create($this->getCurveOid())
),
BitString::create($this->getUncompressedCoordinates())
);
return $this->pem('PUBLIC KEY', $der->toDER());
}
public function getUncompressedCoordinates(): string
{
return "\x04" . $this->x() . $this->y();
}
private function getCurveOid(): string
{
return self::NAMED_CURVE_OID[$this->curveId()];
}
/**
* The registry value of a supported curve, or null when the value denotes no curve this class supports.
*/
private static function toCurveId(mixed $curve): ?int
{
if (is_int($curve)) {
return in_array($curve, self::SUPPORTED_CURVES_INT, true) ? $curve : null;
}
return is_string($curve) ? (self::CURVE_NAME_TO_ID[$curve] ?? null) : null;
}
}

308
vendor/web-auth/cose-lib/src/Key/Key.php vendored Normal file
View file

@ -0,0 +1,308 @@
<?php
declare(strict_types=1);
namespace Cose\Key;
use function array_key_exists;
use function array_values;
use const FILTER_VALIDATE_INT;
use function filter_var;
use function implode;
use function in_array;
use InvalidArgumentException;
use function is_array;
use function is_int;
use function is_string;
use function preg_match;
use function sprintf;
class Key
{
public const TYPE = 1;
public const TYPE_OKP = 1;
public const TYPE_EC2 = 2;
public const TYPE_RSA = 3;
public const TYPE_OCT = 4;
public const TYPE_NAME_OKP = 'OKP';
public const TYPE_NAME_EC2 = 'EC';
public const TYPE_NAME_RSA = 'RSA';
public const TYPE_NAME_OCT = 'oct';
public const KID = 2;
public const ALG = 3;
public const KEY_OPS = 4;
public const BASE_IV = 5;
/**
* Key operations, RFC 9052 section 7.1, Table 5. They are the values the "key_ops" parameter (label 4) is made of.
*/
public const OP_SIGN = 1;
public const OP_VERIFY = 2;
public const OP_ENCRYPT = 3;
public const OP_DECRYPT = 4;
public const OP_WRAP_KEY = 5;
public const OP_UNWRAP_KEY = 6;
public const OP_DERIVE_KEY = 7;
public const OP_DERIVE_BITS = 8;
public const OP_MAC_CREATE = 9;
public const OP_MAC_VERIFY = 10;
/**
* The names of Table 5. A COSE key carries the integer values, but a key converted from a JWK may carry the text
* names JOSE uses for the same operations, so both are accepted when "key_ops" is read.
*
* @var array<int, string>
*/
private const OP_NAMES = [
self::OP_SIGN => 'sign',
self::OP_VERIFY => 'verify',
self::OP_ENCRYPT => 'encrypt',
self::OP_DECRYPT => 'decrypt',
self::OP_WRAP_KEY => 'wrap key',
self::OP_UNWRAP_KEY => 'unwrap key',
self::OP_DERIVE_KEY => 'derive key',
self::OP_DERIVE_BITS => 'derive bits',
self::OP_MAC_CREATE => 'MAC create',
self::OP_MAC_VERIFY => 'MAC verify',
];
/**
* @var array<int|string, mixed>
*/
private readonly array $data;
/**
* @param array<int|string, mixed> $data
*/
public function __construct(array $data)
{
if (! array_key_exists(self::TYPE, $data)) {
throw new InvalidArgumentException('Invalid key: the type is not defined');
}
// The key type is normalised for every key, the generic one included, so that type() answers with the
// registry value whether the key was decoded from CBOR - where spomky-labs/cbor-php renders an integer as a
// numeric string - or built by hand. Everything that checks a key type, from the subclasses below to the
// MAC algorithms, then compares against Key::TYPE_* and sees the same value on both paths.
$this->data = self::normalizeIntegerEntries($data, self::TYPE);
}
/**
* @param array<int|string, mixed> $data
*/
public static function create(array $data): self
{
return new self($data);
}
/**
* Builds the key class the "kty" of the data designates.
*
* The data is expected to be the output of spomky-labs/cbor-php's normalize(), which renders a CBOR integer as a
* numeric string, or an equivalent PHP array: both the string and the native integer form of a registered key
* type are dispatched, as is its name (RFC 9052, section 7.1, table 4 types "kty" as "tstr / int").
*
* @param array<int|string, mixed> $data
*/
public static function createFromData(array $data): self
{
if (! array_key_exists(self::TYPE, $data)) {
throw new InvalidArgumentException('Invalid key: the type is not defined');
}
return match ($data[self::TYPE]) {
self::TYPE_OKP, '1', self::TYPE_NAME_OKP => new OkpKey($data),
self::TYPE_EC2, '2', self::TYPE_NAME_EC2 => new Ec2Key($data),
self::TYPE_RSA, '3', self::TYPE_NAME_RSA => new RsaKey($data),
self::TYPE_OCT, '4', self::TYPE_NAME_OCT => new SymmetricKey($data),
default => self::create($data),
};
}
public function type(): int|string
{
return $this->data[self::TYPE];
}
/**
* The algorithm identifier the key is restricted to, RFC 9052 section 7.1, label 3.
*
* @throws InvalidArgumentException when the key has no "alg", or when its value is not an algorithm identifier.
* A text value such as "RS256" is not one: the COSE registry is made of
* integers, and casting it would silently yield 0, an identifier no algorithm
* is registered under.
*/
public function alg(): int
{
$alg = $this->get(self::ALG);
if (is_int($alg)) {
return $alg;
}
// An integer written as a string is accepted, as the key constructors do for "kty" and "crv".
if (is_string($alg) && filter_var($alg, FILTER_VALIDATE_INT) !== false) {
return (int) $alg;
}
throw new InvalidArgumentException(
'Invalid key: the "alg" parameter must be an integer algorithm identifier'
);
}
/**
* The operations the key is restricted to, RFC 9052 section 7.1, label 4, or null when it carries no such
* restriction.
*
* @throws InvalidArgumentException when "key_ops" is present but is not an array of integers or text names
* @return list<int|string>|null
*/
public function keyOps(): ?array
{
if (! $this->has(self::KEY_OPS)) {
return null;
}
$keyOps = $this->get(self::KEY_OPS);
if (! is_array($keyOps)) {
throw new InvalidArgumentException('Invalid key: the "key_ops" parameter must be an array');
}
foreach ($keyOps as $keyOp) {
if (! is_int($keyOp) && ! is_string($keyOp)) {
throw new InvalidArgumentException(
'Invalid key: the "key_ops" parameter must only contain integers or text names'
);
}
}
return array_values($keyOps);
}
/**
* Whether the restrictions the key carries allow the operation to be performed with the given algorithm.
*
* @see self::assertUsableWith() for the conditions and the specifications behind them
*/
public function isUsableWith(int $algorithmIdentifier, int $operation): bool
{
try {
$this->assertUsableWith($algorithmIdentifier, $operation);
} catch (InvalidArgumentException) {
return false;
}
return true;
}
/**
* RFC 9052, section 7.1: a key that carries "alg" (label 3) MUST NOT be used with another algorithm - "If the
* algorithms do not match, then this key object MUST NOT be used to perform the cryptographic operation" - and
* one that carries "key_ops" (label 4) MUST list the operation being performed. RFC 9053 sections 2.1, 2.2 and
* 3.1 repeat both as a per-algorithm requirement for ECDSA, EdDSA and HMAC.
*
* The comparison is a plain equality of identifiers: the fully-specified identifiers of RFC 9864 and their
* polymorphic counterparts are distinct values here, ES256 (-7) and ESP256 (-9) among them. Section 7 of that
* RFC asks for it - "A cryptographic key MUST be used with only a single algorithm unless the use of the same
* key with different algorithms is proven secure." A caller who wants one key to serve both removes label 3
* from the key data, which is an explicit act.
*
* A key that carries neither parameter is usable with every algorithm and for every operation.
*
* @throws InvalidArgumentException when the key forbids the combination
*
* @see https://www.rfc-editor.org/rfc/rfc9052.html#section-7.1
*/
public function assertUsableWith(int $algorithmIdentifier, int $operation): void
{
if ($this->has(self::ALG) && $this->alg() !== $algorithmIdentifier) {
throw new InvalidArgumentException(sprintf(
'The key is restricted to the algorithm %d and cannot be used with the algorithm %d',
$this->alg(),
$algorithmIdentifier
));
}
$keyOps = $this->keyOps();
if ($keyOps === null) {
return;
}
$name = self::OP_NAMES[$operation] ?? throw new InvalidArgumentException(sprintf(
'Unknown key operation %d. Expected one of: %s',
$operation,
implode(', ', self::OP_NAMES)
));
if (! in_array($operation, $keyOps, true) && ! in_array($name, $keyOps, true)) {
throw new InvalidArgumentException(sprintf('The key does not allow the "%s" operation', $name));
}
}
/**
* @return array<int|string, mixed>
*/
public function getData(): array
{
return $this->data;
}
public function has(int|string $key): bool
{
return array_key_exists($key, $this->data);
}
public function get(int|string $key): mixed
{
if (! array_key_exists($key, $this->data)) {
throw new InvalidArgumentException(sprintf('The key has no data at index %d', $key));
}
return $this->data[$key];
}
/**
* spomky-labs/cbor-php normalises a CBOR integer to a numeric string (UnsignedIntegerObject::normalize()), so a
* key decoded from CBOR carries its "kty" and its "crv" as such a string. Each listed entry that holds one is
* replaced by the integer it denotes, before anything compares it against a registry value.
*
* Only an integer-looking string is converted. A float, or a string such as "1.5", " 1" or "4abc", is left as it
* is so that the checks that follow reject it, instead of a lenient cast silently turning it into a valid
* identifier.
*
* @param array<int|string, mixed> $data
* @return array<int|string, mixed>
*/
protected static function normalizeIntegerEntries(array $data, int|string ...$keys): array
{
foreach ($keys as $key) {
if (array_key_exists($key, $data) && is_string($data[$key])
&& preg_match('/^-?\\d+$/', $data[$key]) === 1) {
$data[$key] = (int) $data[$key];
}
}
return $data;
}
protected function pem(string $type, string $der): string
{
return sprintf("-----BEGIN %s-----\n", strtoupper($type)) .
chunk_split(base64_encode($der), 64, "\n") .
sprintf("-----END %s-----\n", strtoupper($type));
}
}

View file

@ -0,0 +1,251 @@
<?php
declare(strict_types=1);
namespace Cose\Key;
use function array_key_exists;
use function extension_loaded;
use function in_array;
use InvalidArgumentException;
use function is_int;
use function is_string;
use RuntimeException;
use function sodium_crypto_scalarmult_base;
use function sodium_crypto_sign_publickey;
use function sodium_crypto_sign_seed_keypair;
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
use SpomkyLabs\Pki\ASN1\Type\Primitive\BitString;
use SpomkyLabs\Pki\ASN1\Type\Primitive\Integer;
use SpomkyLabs\Pki\ASN1\Type\Primitive\ObjectIdentifier;
use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
use function strlen;
/**
* @final
* @see \Cose\Tests\Key\OkpKeyTest
*/
class OkpKey extends Key
{
final public const CURVE_X25519 = 4;
final public const CURVE_X448 = 5;
final public const CURVE_ED25519 = 6;
final public const CURVE_ED448 = 7;
final public const CURVE_NAME_X25519 = 'X25519';
final public const CURVE_NAME_X448 = 'X448';
final public const CURVE_NAME_ED25519 = 'Ed25519';
final public const CURVE_NAME_ED448 = 'Ed448';
final public const DATA_CURVE = -1;
final public const DATA_X = -2;
final public const DATA_D = -4;
private const SUPPORTED_CURVES_INT = [
self::CURVE_X25519,
self::CURVE_X448,
self::CURVE_ED25519,
self::CURVE_ED448,
];
/**
* RFC 9053, section 7.2, table 20 types "crv" as "int / tstr": a curve may be named instead of numbered. Each of
* these names maps to the identifier of the "COSE Elliptic Curves" registry that curveId() exposes.
*
* @var array<string, int>
*/
private const CURVE_NAME_TO_ID = [
self::CURVE_NAME_X25519 => self::CURVE_X25519,
self::CURVE_NAME_X448 => self::CURVE_X448,
self::CURVE_NAME_ED25519 => self::CURVE_ED25519,
self::CURVE_NAME_ED448 => self::CURVE_ED448,
];
/**
* RFC 8032 section 5.1.5 / 5.2.5 for the Edwards curves and RFC 7748 section 5 for the Montgomery ones: the
* public key and the private scalar are byte strings of exactly this length.
*/
private const CURVE_KEY_LENGTH = [
self::CURVE_X25519 => 32,
self::CURVE_X448 => 56,
self::CURVE_ED25519 => 32,
self::CURVE_ED448 => 57,
];
/**
* The curves whose public key the Sodium extension can recompute from the private one. Ed448 and X448 have no
* such primitive in PHP, so a key on those curves still has to carry its "x".
*/
private const DERIVABLE_CURVES = [
self::CURVE_X25519,
self::CURVE_ED25519,
];
private const CURVE_OID = [
self::CURVE_X25519 => '1.3.101.110',
self::CURVE_X448 => '1.3.101.111',
self::CURVE_ED25519 => '1.3.101.112',
self::CURVE_ED448 => '1.3.101.113',
];
/**
* @param array<int|string, mixed> $data
*/
public function __construct(array $data)
{
// Everything below is read from attacker-supplied CBOR: each entry is checked to be present and of the
// expected PHP type before it is used, so that a malformed key always leaves through the
// InvalidArgumentException this library documents rather than through a warning, a TypeError or an Error.
$data = self::normalizeIntegerEntries($data, self::DATA_CURVE, self::TYPE);
parent::__construct($data);
if ($data[self::TYPE] !== self::TYPE_OKP && $data[self::TYPE] !== self::TYPE_NAME_OKP) {
throw new InvalidArgumentException('Invalid OKP key. The key type does not correspond to an OKP key');
}
// RFC 9053 section 7.2: "d" is the authoritative private key material and "x" is only RECOMMENDED for a
// private key, "it can be recomputed from the required elements". A private key carrying "crv" and "d"
// alone is therefore valid, and is the safest way to build a signing key: nothing can hand over an "x"
// inconsistent with the seed.
if (! isset($data[self::DATA_CURVE]) || (! isset($data[self::DATA_X]) && ! isset($data[self::DATA_D]))) {
throw new InvalidArgumentException('Invalid OKP key. The curve or the "x" coordinate is missing');
}
// The curve is checked first: the key lengths below are read from a table indexed by the curve.
$curveId = self::toCurveId($data[self::DATA_CURVE]);
if ($curveId === null) {
throw new InvalidArgumentException('The curve is not supported');
}
// RFC 8032 section 5.1.5 / 5.2.5 and RFC 7748 section 5: both halves are byte strings of this exact length.
$length = self::CURVE_KEY_LENGTH[$curveId];
if (array_key_exists(self::DATA_X, $data)
&& (! is_string($data[self::DATA_X]) || strlen($data[self::DATA_X]) !== $length)) {
throw new InvalidArgumentException('Invalid length for x coordinate');
}
if (array_key_exists(self::DATA_D, $data)
&& (! is_string($data[self::DATA_D]) || strlen($data[self::DATA_D]) !== $length)) {
throw new InvalidArgumentException('Invalid length for d');
}
}
/**
* @param array<int|string, mixed> $data
*/
public static function create(array $data): self
{
return new self($data);
}
public function x(): string
{
if ($this->has(self::DATA_X)) {
return $this->get(self::DATA_X);
}
return $this->derivePublicKey();
}
public function isPrivate(): bool
{
return array_key_exists(self::DATA_D, $this->getData());
}
public function d(): string
{
if (! $this->isPrivate()) {
throw new InvalidArgumentException('The key is not private.');
}
return $this->get(self::DATA_D);
}
/**
* The curve as the key carries it, which RFC 9053 section 7.2 allows to be either the identifier of the "COSE
* Elliptic Curves" registry or a name. Use curveId() to get the identifier whatever form was supplied.
*/
public function curve(): int|string
{
return $this->get(self::DATA_CURVE);
}
/**
* The value of the curve in the IANA "COSE Elliptic Curves" registry, whichever of the two forms the key uses.
*/
public function curveId(): int
{
$curve = $this->curve();
return is_int($curve) ? $curve : self::CURVE_NAME_TO_ID[$curve];
}
public function toPublic(): self
{
$data = $this->getData();
$data[self::DATA_X] = $this->x();
unset($data[self::DATA_D]);
return new self($data);
}
/**
* Recomputes the public key from the private one, as RFC 9053 section 7.2 allows when "x" was omitted.
*/
private function derivePublicKey(): string
{
$curve = $this->curveId();
if (! in_array($curve, self::DERIVABLE_CURVES, true)) {
throw new InvalidArgumentException(
'The "x" coordinate is missing and cannot be computed from "d" for this curve'
);
}
if (! extension_loaded('sodium')) {
throw new RuntimeException(
'The "x" coordinate is missing and computing it from "d" requires the Sodium extension, which is not loaded.'
);
}
$d = $this->d();
return $curve === self::CURVE_X25519
? sodium_crypto_scalarmult_base($d)
: sodium_crypto_sign_publickey(sodium_crypto_sign_seed_keypair($d));
}
/**
* The registry value of a supported curve, or null when the value denotes no curve this class supports.
*/
private static function toCurveId(mixed $curve): ?int
{
if (is_int($curve)) {
return in_array($curve, self::SUPPORTED_CURVES_INT, true) ? $curve : null;
}
return is_string($curve) ? (self::CURVE_NAME_TO_ID[$curve] ?? null) : null;
}
/**
* Returns the key as a PEM encoded RFC 8410 OneAsymmetricKey (private) or SubjectPublicKeyInfo (public) structure.
*/
public function asPEM(): string
{
$oid = ObjectIdentifier::create(self::CURVE_OID[$this->curveId()]);
if ($this->isPrivate()) {
$der = Sequence::create(
Integer::create(0),
Sequence::create($oid),
OctetString::create(OctetString::create($this->d())->toDER())
);
return $this->pem('PRIVATE KEY', $der->toDER());
}
$der = Sequence::create(Sequence::create($oid), BitString::create($this->x()));
return $this->pem('PUBLIC KEY', $der->toDER());
}
}

View file

@ -0,0 +1,273 @@
<?php
declare(strict_types=1);
namespace Cose\Key;
use function array_key_exists;
use function in_array;
use function intdiv;
use InvalidArgumentException;
use function ltrim;
use function ord;
use SpomkyLabs\Pki\CryptoEncoding\PEM;
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Asymmetric\ECPublicKeyAlgorithmIdentifier;
use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PublicKeyInfo;
use SpomkyLabs\Pki\X509\Certificate\Certificate;
use function sprintf;
use function str_contains;
use function strlen;
use function substr;
use Throwable;
/**
* Turns the public key of an X.509 certificate, or a bare SubjectPublicKeyInfo, into the Cose\Key\Key the signature
* algorithms of this library take.
*
* WebAuthn Level 3 sections 8.2 to 8.4 ask a relying party to verify a certificate-based attestation statement "with
* the algorithm specified in alg". Doing so through Algorithms::getOpensslAlgorithmFor() and openssl_verify() only
* covers ECDSA and RSASSA-PKCS1-v1_5, because an OPENSSL_ALGO_* digest implies PKCS #1 v1.5 padding; RSASSA-PSS and
* the EdDSA family cannot be expressed that way. This loader is the missing half of the other route: it produces the
* key, and the Signature class registered for the identifier does the verification. See
* Cose\Algorithm\Signature\CertificateSignatureVerifier for the two put together.
*
* Both methods accept PEM or raw DER.
*
* @see \Cose\Tests\Key\PublicKeyLoaderTest
*/
final class PublicKeyLoader
{
/**
* The named curves of RFC 5480, section 2.1.1.1 and RFC 5639, section 4.1 this library has a COSE identifier for
* (RFC 9053, section 7.1 and the IANA COSE Elliptic Curves registry).
*/
private const CURVE_OID_TO_COSE_CURVE = [
'1.2.840.10045.3.1.7' => Ec2Key::CURVE_P256,
'1.3.132.0.10' => Ec2Key::CURVE_P256K,
'1.3.132.0.34' => Ec2Key::CURVE_P384,
'1.3.132.0.35' => Ec2Key::CURVE_P521,
'1.3.36.3.3.2.8.1.1.7' => Ec2Key::CURVE_BP256,
'1.3.36.3.3.2.8.1.1.9' => Ec2Key::CURVE_BP320,
'1.3.36.3.3.2.8.1.1.11' => Ec2Key::CURVE_BP384,
'1.3.36.3.3.2.8.1.1.13' => Ec2Key::CURVE_BP512,
];
/**
* The RFC 8410, section 3 algorithm identifiers, whose subjectPublicKey is the public key itself.
*/
private const RFC8410_OID_TO_COSE_CURVE = [
'1.3.101.110' => OkpKey::CURVE_X25519,
'1.3.101.111' => OkpKey::CURVE_X448,
'1.3.101.112' => OkpKey::CURVE_ED25519,
'1.3.101.113' => OkpKey::CURVE_ED448,
];
/**
* rsaEncryption (RFC 8017, appendix A.1) and RSASSA-PSS (RFC 4055, section 1.2). The latter carries the same
* RSAPublicKey structure behind its own object identifier; the COSE key knows nothing of the padding, which the
* algorithm identifier of the signature decides, so both are read the same way.
*/
private const RSA_OIDS = ['1.2.840.113549.1.1.1', '1.2.840.113549.1.1.10'];
/**
* id-ecPublicKey, RFC 5480, section 2.1.1.
*/
private const OID_EC_PUBLIC_KEY = '1.2.840.10045.2.1';
private const DER_TAG_SEQUENCE = 0x30;
private const DER_TAG_INTEGER = 0x02;
/**
* The public key of an X.509 certificate, PEM or DER encoded.
*
* @throws InvalidArgumentException when the certificate cannot be read, or carries a key this library has no
* COSE representation for
*/
public static function fromCertificate(string $certificate): Key
{
try {
$parsed = Certificate::fromDER(self::der($certificate, PEM::TYPE_CERTIFICATE));
} catch (Throwable $throwable) {
throw new InvalidArgumentException('Unable to read the certificate', 0, $throwable);
}
return self::fromPublicKeyInfo($parsed->tbsCertificate()->subjectPublicKeyInfo());
}
/**
* A bare SubjectPublicKeyInfo (RFC 5280, section 4.1.2.7), PEM or DER encoded.
*
* @throws InvalidArgumentException when the structure cannot be read, or carries a key this library has no COSE
* representation for
*/
public static function fromSubjectPublicKeyInfo(string $subjectPublicKeyInfo): Key
{
try {
$parsed = PublicKeyInfo::fromDER(self::der($subjectPublicKeyInfo, PEM::TYPE_PUBLIC_KEY));
} catch (Throwable $throwable) {
throw new InvalidArgumentException('Unable to read the public key', 0, $throwable);
}
return self::fromPublicKeyInfo($parsed);
}
private static function fromPublicKeyInfo(PublicKeyInfo $publicKeyInfo): Key
{
$algorithm = $publicKeyInfo->algorithmIdentifier();
$oid = $algorithm->oid();
$publicKey = $publicKeyInfo->publicKeyData()
->string();
if (in_array($oid, self::RSA_OIDS, true)) {
return self::rsaKey($publicKey);
}
if (array_key_exists($oid, self::RFC8410_OID_TO_COSE_CURVE)) {
return OkpKey::create([
Key::TYPE => Key::TYPE_OKP,
OkpKey::DATA_CURVE => self::RFC8410_OID_TO_COSE_CURVE[$oid],
OkpKey::DATA_X => $publicKey,
]);
}
if ($oid === self::OID_EC_PUBLIC_KEY && $algorithm instanceof ECPublicKeyAlgorithmIdentifier) {
return self::ec2Key($algorithm->namedCurve(), $publicKey);
}
throw new InvalidArgumentException(sprintf('Unsupported public key algorithm "%s"', $oid));
}
private static function ec2Key(string $namedCurve, string $ecPoint): Ec2Key
{
if (! array_key_exists($namedCurve, self::CURVE_OID_TO_COSE_CURVE)) {
throw new InvalidArgumentException(sprintf('Unsupported elliptic curve "%s"', $namedCurve));
}
// RFC 5480, section 2.2: the subjectPublicKey is the ECPoint of SEC 1, section 2.3.3. Only its uncompressed
// form is read here, as it is the only one Cose\Key\Ec2Key stores; decompressing a point would mean
// computing a square root modulo the field prime for every curve this library names.
if ($ecPoint === '' || ord($ecPoint[0]) !== 0x04) {
throw new InvalidArgumentException(
'Unsupported elliptic curve public key: only the uncompressed point format is supported'
);
}
$coordinates = substr($ecPoint, 1);
if (strlen($coordinates) === 0 || strlen($coordinates) % 2 !== 0) {
throw new InvalidArgumentException('Invalid elliptic curve public key');
}
$length = intdiv(strlen($coordinates), 2);
// Ec2Key rejects coordinates whose length does not match the curve.
return Ec2Key::create([
Key::TYPE => Key::TYPE_EC2,
Ec2Key::DATA_CURVE => self::CURVE_OID_TO_COSE_CURVE[$namedCurve],
Ec2Key::DATA_X => substr($coordinates, 0, $length),
Ec2Key::DATA_Y => substr($coordinates, $length),
]);
}
/**
* Reads the RSAPublicKey of RFC 8017, appendix A.1.1 - SEQUENCE { modulus INTEGER, publicExponent INTEGER } - and
* stores both integers as the unsigned big-endian octet strings RFC 8230, section 4 defines a COSE RSA key with.
*
* The two INTEGERs are taken as the octet strings they already are, and never turned into numbers: brick/math
* falls back to a pure PHP calculator whenever neither ext-gmp nor ext-bcmath is loaded, and its generic base
* conversion is superlinear, so decoding an attacker supplied modulus into a decimal string and back would cost
* more than the verification it precedes. Cose\Key\RsaKey builds its DER the same way, and for the same reason.
*/
private static function rsaKey(string $rsaPublicKey): RsaKey
{
$offset = 0;
$content = self::readValue($rsaPublicKey, self::DER_TAG_SEQUENCE, $offset);
if ($offset !== strlen($rsaPublicKey)) {
throw new InvalidArgumentException('Invalid RSA public key: trailing data');
}
$inner = 0;
$modulus = self::readValue($content, self::DER_TAG_INTEGER, $inner);
$exponent = self::readValue($content, self::DER_TAG_INTEGER, $inner);
if ($inner !== strlen($content)) {
throw new InvalidArgumentException('Invalid RSA public key: trailing data');
}
return RsaKey::create([
Key::TYPE => Key::TYPE_RSA,
RsaKey::DATA_N => self::magnitude($modulus, 'modulus'),
RsaKey::DATA_E => self::magnitude($exponent, 'public exponent'),
]);
}
/**
* The content octets of the TLV of the expected tag starting at $offset, which is advanced past the whole TLV.
*
* Only the definite form of X.690, section 8.1.3 is accepted, which is all DER allows (section 10.1).
*/
private static function readValue(string $der, int $expectedTag, int &$offset): string
{
if (strlen($der) < $offset + 2) {
throw new InvalidArgumentException('Invalid RSA public key: truncated structure');
}
if (ord($der[$offset]) !== $expectedTag) {
throw new InvalidArgumentException('Invalid RSA public key: unexpected structure');
}
++$offset;
$length = ord($der[$offset]);
++$offset;
if ($length > 0x80) {
$lengthOfLength = $length & 0x7F;
// A length that needs more than four octets describes a value no PHP string can hold anyway.
if ($lengthOfLength > 4 || strlen($der) < $offset + $lengthOfLength) {
throw new InvalidArgumentException('Invalid RSA public key: unsupported length');
}
$length = 0;
for ($i = 0; $i < $lengthOfLength; ++$i) {
$length = ($length << 8) | ord($der[$offset + $i]);
}
$offset += $lengthOfLength;
} elseif ($length === 0x80) {
// X.690, section 10.1: the indefinite form is not DER.
throw new InvalidArgumentException('Invalid RSA public key: indefinite length');
}
if (strlen($der) < $offset + $length) {
throw new InvalidArgumentException('Invalid RSA public key: truncated structure');
}
$content = substr($der, $offset, $length);
$offset += $length;
return $content;
}
/**
* X.690, section 8.3.2 encodes the content octets of an INTEGER in two's complement, so a leading 0x00 is only
* there to keep a non-negative value from reading as a negative one; RFC 8230, section 4 stores the magnitude
* alone. A value whose first bit is set is negative, which no RSA parameter ever is.
*/
private static function magnitude(string $integer, string $name): string
{
if ($integer === '') {
throw new InvalidArgumentException(sprintf('Invalid RSA public key: the %s is empty', $name));
}
if ((ord($integer[0]) & 0x80) !== 0) {
throw new InvalidArgumentException(sprintf('Invalid RSA public key: the %s is negative', $name));
}
$magnitude = ltrim($integer, "\x00");
if ($magnitude === '') {
throw new InvalidArgumentException(sprintf('Invalid RSA public key: the %s is zero', $name));
}
return $magnitude;
}
/**
* The DER of a structure given either as PEM or as DER already.
*/
private static function der(string $data, string $pemType): string
{
if (! str_contains($data, '-----BEGIN')) {
return $data;
}
$pem = PEM::fromString($data);
if ($pem->type() !== $pemType) {
throw new InvalidArgumentException(sprintf('Invalid PEM type "%s", expected "%s"', $pem->type(), $pemType));
}
return $pem->data();
}
}

View file

@ -0,0 +1,362 @@
<?php
declare(strict_types=1);
namespace Cose\Key;
use function array_key_exists;
use function base64_encode;
use function chunk_split;
use function implode;
use function in_array;
use InvalidArgumentException;
use function is_string;
use function ltrim;
use function ord;
use function pack;
use function sprintf;
use function strlen;
use function trim;
/**
* @final
* @see \Cose\Tests\Key\RsaKeyTest
*/
class RsaKey extends Key
{
final public const DATA_N = -1;
final public const DATA_E = -2;
final public const DATA_D = -3;
final public const DATA_P = -4;
final public const DATA_Q = -5;
final public const DATA_DP = -6;
final public const DATA_DQ = -7;
final public const DATA_QI = -8;
final public const DATA_OTHER = -9;
final public const DATA_RI = -10;
final public const DATA_DI = -11;
final public const DATA_TI = -12;
/**
* The DER of the rsaEncryption object identifier, 1.2.840.113549.1.1.1 (RFC 8017, appendix A.1).
*/
private const OID_RSA_ENCRYPTION = "\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01";
private const DER_NULL = "\x05\x00";
/**
* @var array<int>
*/
private const PRIVATE_PARAMETERS = [
self::DATA_D,
self::DATA_P,
self::DATA_Q,
self::DATA_DP,
self::DATA_DQ,
self::DATA_QI,
];
/**
* @param array<int|string, mixed> $data
*/
public function __construct(array $data)
{
$data = self::normalizeIntegerEntries($data, self::TYPE);
parent::__construct($data);
if ($data[self::TYPE] !== self::TYPE_RSA && $data[self::TYPE] !== self::TYPE_NAME_RSA) {
throw new InvalidArgumentException('Invalid RSA key. The key type does not correspond to a RSA key');
}
if (! isset($data[self::DATA_N], $data[self::DATA_E])) {
throw new InvalidArgumentException('Invalid RSA key. The modulus or the exponent is missing');
}
$modulus = $data[self::DATA_N];
$exponent = $data[self::DATA_E];
if (! is_string($modulus) || $modulus === '' || ! is_string($exponent) || $exponent === '') {
throw new InvalidArgumentException(
'Invalid RSA key. The modulus and the exponent shall be non-empty byte strings'
);
}
if (ltrim($modulus, "\0") === '') {
throw new InvalidArgumentException('Invalid RSA key. The modulus shall not be zero');
}
foreach (self::PRIVATE_PARAMETERS as $parameter) {
if (array_key_exists($parameter, $data) && ! is_string($data[$parameter])) {
throw new InvalidArgumentException('Invalid RSA key. The private parameters shall be byte strings');
}
}
}
/**
* @param array<int|string, mixed> $data
*/
public static function create(array $data): self
{
return new self($data);
}
public function n(): string
{
return $this->get(self::DATA_N);
}
public function e(): string
{
return $this->get(self::DATA_E);
}
public function d(): string
{
$this->checkKeyIsPrivate();
return $this->get(self::DATA_D);
}
public function p(): string
{
$this->checkKeyIsPrivate();
return $this->get(self::DATA_P);
}
public function q(): string
{
$this->checkKeyIsPrivate();
return $this->get(self::DATA_Q);
}
public function dP(): string
{
$this->checkKeyIsPrivate();
return $this->get(self::DATA_DP);
}
public function dQ(): string
{
$this->checkKeyIsPrivate();
return $this->get(self::DATA_DQ);
}
public function QInv(): string
{
$this->checkKeyIsPrivate();
return $this->get(self::DATA_QI);
}
/**
* The "other prime infos" of a multi-prime key (RFC 8230, section 4): one map per prime from the third one on,
* each holding the DATA_RI, DATA_DI and DATA_TI entries.
*
* @return array<int, array<int, string>>
*/
public function other(): array
{
$this->checkKeyIsPrivate();
return $this->get(self::DATA_OTHER);
}
public function rI(): string
{
$this->checkKeyIsPrivate();
return $this->get(self::DATA_RI);
}
public function dI(): string
{
$this->checkKeyIsPrivate();
return $this->get(self::DATA_DI);
}
public function tI(): string
{
$this->checkKeyIsPrivate();
return $this->get(self::DATA_TI);
}
public function hasPrimes(): bool
{
return $this->has(self::DATA_P) && $this->has(self::DATA_Q);
}
/**
* @return string[]
*/
public function primes(): array
{
return [$this->p(), $this->q()];
}
public function hasExponents(): bool
{
return $this->has(self::DATA_DP) && $this->has(self::DATA_DQ);
}
/**
* @return string[]
*/
public function exponents(): array
{
return [$this->dP(), $this->dQ()];
}
public function hasCoefficient(): bool
{
return $this->has(self::DATA_QI);
}
public function isPublic(): bool
{
return ! $this->isPrivate();
}
public function isPrivate(): bool
{
return array_key_exists(self::DATA_D, $this->getData());
}
/**
* A key carrying "other prime infos" (RFC 8230, section 4) is exported as a version 0, two-prime RSAPrivateKey in
* which p*q is not the modulus: the PKCS #1 OtherPrimeInfos sequence is not emitted. RS1, RS256, RS384 and RS512
* keep working with such a key only because OpenSSL checks its CRT result against s^e mod n and falls back to
* m^d mod n when the two disagree. RSASSA-PSS does not go through this method and handles the additional primes
* itself.
*
* The DER is built from the octet strings of the key as they are, without ever turning them into numbers. X.690,
* section 8.3 defines the content octets of an ASN.1 INTEGER as the two's complement big-endian representation of
* its value, which for a non-negative integer is its raw big-endian magnitude with a leading 0x00 whenever the
* first bit is set - and RFC 8230, section 4 already stores every parameter of a COSE RSA key in exactly that
* form. Routing them through a big integer library instead would convert each of them to a decimal string and
* back: brick/math falls back to a pure PHP calculator whenever neither ext-gmp nor ext-bcmath is loaded, and its
* generic base conversion is superlinear, so that round trip alone costs seconds of CPU on a large modulus - paid
* on every verification, before OpenSSL sees anything.
*/
public function asPem(): string
{
if ($this->isPrivate()) {
return self::toPem('RSA PRIVATE KEY', self::derSequence(
// RFC 8017, appendix A.1.2: version is 0 for a two-prime key.
self::derInteger("\0"),
self::derInteger($this->n()),
self::derInteger($this->e()),
self::derInteger($this->d()),
self::derInteger($this->p()),
self::derInteger($this->q()),
self::derInteger($this->dP()),
self::derInteger($this->dQ()),
self::derInteger($this->QInv())
));
}
// RFC 5280, section 4.1: SubjectPublicKeyInfo wraps the DER of an RFC 8017 RSAPublicKey in a BIT STRING,
// behind the rsaEncryption algorithm identifier and its mandatory NULL parameters (RFC 3279, section 2.3.1).
$rsaPublicKey = self::derSequence(self::derInteger($this->n()), self::derInteger($this->e()));
return self::toPem('PUBLIC KEY', self::derSequence(
self::derSequence(self::OID_RSA_ENCRYPTION, self::DER_NULL),
self::derBitString($rsaPublicKey)
));
}
public function toPublic(): static
{
$toBeRemoved = [
self::DATA_D,
self::DATA_P,
self::DATA_Q,
self::DATA_DP,
self::DATA_DQ,
self::DATA_QI,
self::DATA_OTHER,
self::DATA_RI,
self::DATA_DI,
self::DATA_TI,
];
$data = $this->getData();
foreach ($data as $k => $v) {
if (in_array($k, $toBeRemoved, true)) {
unset($data[$k]);
}
}
return new static($data);
}
private function checkKeyIsPrivate(): void
{
if (! $this->isPrivate()) {
throw new InvalidArgumentException('The key is not private.');
}
}
/**
* An ASN.1 INTEGER holding the non-negative integer whose big-endian magnitude is $value (X.690, section 8.3).
*/
private static function derInteger(string $value): string
{
$value = ltrim($value, "\0");
if ($value === '') {
// Section 8.3.1: the content octets are never empty, so zero is a single 0x00 octet.
$value = "\0";
} elseif ((ord($value[0]) & 0x80) !== 0) {
// Section 8.3.2: without this octet the value would be read as a negative number.
$value = "\0" . $value;
}
return self::der(0x02, $value);
}
private static function derSequence(string ...$elements): string
{
return self::der(0x30, implode('', $elements));
}
private static function derBitString(string $value): string
{
// X.690, section 8.6.2.2: the leading octet is the number of unused bits of the final octet, none here since
// the value being wrapped is a whole number of octets.
return self::der(0x03, "\0" . $value);
}
private static function der(int $tag, string $content): string
{
$length = strlen($content);
if ($length < 0x80) {
// X.690, section 8.1.3.4: short form.
$encodedLength = pack('C', $length);
} else {
// Section 8.1.3.5: long form, the length itself in the fewest octets that can hold it.
$octets = ltrim(pack('J', $length), "\0");
$encodedLength = pack('C', 0x80 | strlen($octets)) . $octets;
}
return pack('C', $tag) . $encodedLength . $content;
}
private static function toPem(string $type, string $der): string
{
return sprintf(
"-----BEGIN %s-----\n%s\n-----END %s-----",
$type,
trim(chunk_split(base64_encode($der), 64, "\n")),
$type
);
}
}

View file

@ -0,0 +1,260 @@
<?php
declare(strict_types=1);
namespace Cose\Key;
use InvalidArgumentException;
use function ltrim;
use function ord;
use function sprintf;
use function strcmp;
use function strlen;
use Throwable;
/**
* Checks an RSA key against the constraints the COSE and WebAuthn algorithm registrations rely on.
*
* RFC 8812 registers the RSA algorithms for WebAuthn and defers to RFC 8230, whose section 6.1 states that "a key
* size of 2048 bits or larger MUST be used with these algorithms" and that implementations "SHOULD be able to encrypt
* and decrypt with modulus between 2048 and 16K bits in length". The public exponent constraints come from RFC 8017,
* section 3.1, which defines it as an odd integer between 3 and n - 1.
*
* Two families of constraints are applied by the RSA algorithms of this library to every key they are given, both
* through Cose\Algorithm\Signature\RSA\RSA and Cose\Algorithm\Signature\RSA\PSSRSA: the public parameter constraints
* of RFC 8017, section 3.1 (checkPublicParameters()), and the upper bounds on the size of the key
* (checkLengthBounds()). Neither depends on a policy - an RSA operation costs an amount of CPU proportional to the
* size of the key it is given, and that key is attacker supplied whenever it comes from the wire.
*
* The *minimum* modulus length is the policy choice, and the algorithms apply it too: each of them runs check() on
* every key it is handed, with the validator it was created with or, by default, with create(). Legacy
* authenticators holding 1024 bit keys exist, so the default bound only emits an E_USER_WARNING in 4.x and will
* throw as of v5.0.0; a validator passed explicitly to the algorithm - RS256::create(RsaKeyValidator::create(
* minimumModulusLength: 1024)) - is enforced with an exception right away, because the caller chose the bound.
*
* Every check below reads the parameters as the octet strings they are. Turning one into a number is a base
* conversion, and brick/math falls back to a pure PHP calculator - whose generic base conversion is superlinear -
* whenever neither ext-gmp nor ext-bcmath is loaded. A validator that runs before every operation must not grow
* expensive with the size of the key it is handed.
*
* @see https://datatracker.ietf.org/doc/html/rfc8812
* @see https://www.rfc-editor.org/rfc/rfc8230#section-6.1
* @see \Cose\Tests\Key\RsaKeyValidatorTest
*/
final class RsaKeyValidator
{
/**
* The smallest modulus length RFC 8230 allows, in bits.
*/
public const MINIMUM_MODULUS_LENGTH = 2048;
/**
* The largest modulus length RFC 8230 expects implementations to cope with, in bits.
*/
public const MAXIMUM_MODULUS_LENGTH = 16384;
/**
* The largest public exponent length any RSA operation of this library accepts, in bits.
*
* FIPS 186-5, appendix A.1.1 requires 2^16 < e < 2^256 of a generated key; RFC 8017, section 3.1 places no upper
* bound at all, which is precisely why one has to be imposed here. The public operation is a modular
* exponentiation whose cost is proportional to the length of the exponent, so an unbounded e is an unbounded
* amount of work: at the largest modulus RFC 8230 asks for, e = n - 2 costs sixty four times as much as this
* bound allows.
*/
public const MAXIMUM_EXPONENT_LENGTH = 256;
/**
* The warning an RSA algorithm emits when the key it is given is rejected by the validator it defaulted to. Its
* only placeholder receives the message of the underlying InvalidArgumentException.
*
* @see \Cose\Algorithm\Signature\RSA\RsaKeyPolicy
*/
public const WEAK_KEY_MESSAGE = 'The RSA key does not satisfy RFC 8230 section 6.1: %s. Accept it explicitly with "RsaKeyValidator::create(minimumModulusLength: 1024)"; as of v5.0.0, it will be rejected with an exception.';
private function __construct(
private readonly int $minimumModulusLength,
private readonly int $maximumModulusLength
) {
if ($minimumModulusLength < 1) {
throw new InvalidArgumentException('The minimum modulus length shall be a positive integer');
}
if ($maximumModulusLength < $minimumModulusLength) {
throw new InvalidArgumentException(
'The maximum modulus length shall be greater than or equal to the minimum modulus length'
);
}
}
public static function create(
int $minimumModulusLength = self::MINIMUM_MODULUS_LENGTH,
int $maximumModulusLength = self::MAXIMUM_MODULUS_LENGTH
): self {
return new self($minimumModulusLength, $maximumModulusLength);
}
/**
* Returns the length of the modulus of the key, in bits.
*/
public static function modulusLength(RsaKey $key): int
{
return self::bitLength($key->n());
}
/**
* Returns the length of the public exponent of the key, in bits.
*/
public static function exponentLength(RsaKey $key): int
{
return self::bitLength($key->e());
}
/**
* The upper bounds on the size of a key that every RSA algorithm of this library applies before it does anything
* with it. They are not a policy the caller opts into: an RSA operation costs an amount of CPU proportional to
* the size of the modulus and of the exponent it is given, both of which are attacker supplied whenever the key
* travels on the wire, and that cost is paid before anything is known about the signature. RFC 8230, section 6.1
* asks for exactly this: "It is highly recommended that checks on the key length be done before starting a
* cryptographic operation."
*
* No minimum is applied here, so that this method never rejects a key an earlier release accepted.
*
* @throws InvalidArgumentException when the key is larger than this library is willing to compute with
*/
public static function checkLengthBounds(RsaKey $key): void
{
self::checkMaximumModulusLength($key, self::MAXIMUM_MODULUS_LENGTH);
self::checkMaximumExponentLength($key);
}
/**
* @throws InvalidArgumentException when the key does not satisfy the constraints
*/
public function check(RsaKey $key): void
{
$modulusLength = self::modulusLength($key);
if ($modulusLength < $this->minimumModulusLength) {
throw new InvalidArgumentException(sprintf(
'The modulus of the key is %d bits long; at least %d bits are required',
$modulusLength,
$this->minimumModulusLength
));
}
self::checkMaximumModulusLength($key, $this->maximumModulusLength);
self::checkPublicParameters($key);
}
/**
* The constraints RFC 8017, section 3.1 places on the public parameters of an RSA key: an odd modulus and a
* public exponent that is an odd integer between 3 and n - 1. Both primitives of section 5.2 are defined under
* the assumption that the key satisfies them, and none of their guarantees survives a key that does not: with
* e = 1 the public operation is the identity map, so a padded message encoding - data that is entirely public -
* is accepted as a signature of the message it encodes.
*
* Unlike the modulus length bounds, these constraints depend on no policy and admit no legitimate exception,
* which is why the RSA algorithms apply them on their own.
*
* @throws InvalidArgumentException when the key does not satisfy the constraints
*/
public static function checkPublicParameters(RsaKey $key): void
{
self::checkModulus($key);
self::checkExponent($key);
}
public function isValid(RsaKey $key): bool
{
try {
$this->check($key);
} catch (Throwable) {
return false;
}
return true;
}
/**
* The modulus is the product of at least two odd primes (RFC 8017, section 3.1), hence odd and non-zero. An even
* modulus is not merely out of specification: taking e-th roots modulo a power of two is easy, so a signature
* under an attacker chosen even modulus can be computed without any private key.
*/
private static function checkModulus(RsaKey $key): void
{
$rawModulus = ltrim($key->n(), "\x00");
if ($rawModulus === '') {
throw new InvalidArgumentException('The modulus of the key shall not be zero');
}
if ((ord($rawModulus[strlen($rawModulus) - 1]) & 1) !== 1) {
throw new InvalidArgumentException('The modulus of the key shall be odd');
}
}
private static function checkExponent(RsaKey $key): void
{
$exponent = ltrim($key->e(), "\x00");
if ($exponent === '' || (ord($exponent[strlen($exponent) - 1]) & 1) !== 1) {
throw new InvalidArgumentException('The public exponent of the key shall be odd');
}
if (strlen($exponent) === 1 && ord($exponent[0]) < 3) {
throw new InvalidArgumentException('The public exponent of the key shall be greater than or equal to 3');
}
if (self::compareMagnitudes($exponent, ltrim($key->n(), "\x00")) >= 0) {
throw new InvalidArgumentException('The public exponent of the key shall be lower than its modulus');
}
self::checkMaximumExponentLength($key);
}
private static function checkMaximumModulusLength(RsaKey $key, int $maximumModulusLength): void
{
$modulusLength = self::modulusLength($key);
if ($modulusLength > $maximumModulusLength) {
throw new InvalidArgumentException(sprintf(
'The modulus of the key is %d bits long; at most %d bits are allowed',
$modulusLength,
$maximumModulusLength
));
}
}
private static function checkMaximumExponentLength(RsaKey $key): void
{
$exponentLength = self::exponentLength($key);
if ($exponentLength > self::MAXIMUM_EXPONENT_LENGTH) {
throw new InvalidArgumentException(sprintf(
'The public exponent of the key is %d bits long; at most %d bits are allowed',
$exponentLength,
self::MAXIMUM_EXPONENT_LENGTH
));
}
}
/**
* Compares two non-negative integers given as big-endian octet strings stripped of their leading zero octets: the
* longer one is the larger, and equal lengths are decided octet by octet.
*/
private static function compareMagnitudes(string $left, string $right): int
{
$byLength = strlen($left) <=> strlen($right);
return $byLength === 0 ? strcmp($left, $right) : $byLength;
}
/**
* The length in bits of the non-negative integer whose big-endian octet string is $value.
*/
private static function bitLength(string $value): int
{
$value = ltrim($value, "\x00");
if ($value === '') {
return 0;
}
$length = (strlen($value) - 1) * 8;
for ($mostSignificantByte = ord($value[0]); $mostSignificantByte > 0; $mostSignificantByte >>= 1) {
++$length;
}
return $length;
}
}

View file

@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace Cose\Key;
use InvalidArgumentException;
use function is_string;
/**
* A symmetric COSE key (RFC 9053, section 7.3).
*
* Table 21 of that section types the key value `k` as a `bstr`, which is what the k() accessor of this class has
* always returned. The constructor enforces the same contract: a `k` that is not a PHP string, or that is empty, is
* rejected where the mistake is easiest to attribute rather than at the first cryptographic operation.
*
* @see https://www.rfc-editor.org/rfc/rfc9053#section-7.3
* @see \Cose\Tests\Key\SymmetricKeyTest
*
* @final
*/
class SymmetricKey extends Key
{
final public const DATA_K = -1;
/**
* @param array<int|string, mixed> $data
*/
public function __construct(array $data)
{
// The three sibling key classes normalise and store the key type; this one used to cast it inside its own
// comparison only, so a key decoded from CBOR kept the string "4" that every HMAC algorithm then rejected.
$data = self::normalizeIntegerEntries($data, self::TYPE);
parent::__construct($data);
if ($data[self::TYPE] !== self::TYPE_OCT && $data[self::TYPE] !== self::TYPE_NAME_OCT) {
throw new InvalidArgumentException(
'Invalid symmetric key. The key type does not correspond to a symmetric key'
);
}
if (! isset($data[self::DATA_K])) {
throw new InvalidArgumentException('Invalid symmetric key. The parameter "k" is missing');
}
if (! is_string($data[self::DATA_K])) {
throw new InvalidArgumentException(
'Invalid symmetric key. The parameter "k" shall be a byte string (CBOR objects shall be normalized first)'
);
}
if ($data[self::DATA_K] === '') {
throw new InvalidArgumentException('Invalid symmetric key. The parameter "k" is empty');
}
}
/**
* @param array<int|string, mixed> $data
*/
public static function create(array $data): self
{
return new self($data);
}
public function k(): string
{
return $this->get(self::DATA_K);
}
}

View file

@ -0,0 +1,125 @@
<?php
declare(strict_types=1);
namespace Cose\Key;
use InvalidArgumentException;
use function is_string;
use function sprintf;
use function strlen;
use Throwable;
/**
* Checks a symmetric key against the constraints the COSE MAC algorithms rely on.
*
* RFC 9053, section 3.1 requires implementations to "validate that the key type, key length, and algorithm are
* correct and appropriate for the entities involved". The key type and the byte string nature of `k` admit no
* exception and are therefore applied by the algorithms themselves: Cose\Algorithm\Mac\Hmac rejects a key that is
* not symmetric, whose `k` is missing, is not a PHP string, or is empty.
*
* The *minimum* key length is the policy choice, and it stays opt-in, exactly like the minimum modulus length of
* RsaKeyValidator: RFC 2104, section 3 only states that a key shorter than the output of the hash function is
* "strongly discouraged", and existing deployments do key HS384/HS512 with 32 bytes. Run this validator explicitly
* on a key before handing it to an algorithm to turn that discouragement into a hard failure today, instead of the
* E_USER_WARNING the algorithms emit.
*
* @see https://www.rfc-editor.org/rfc/rfc9053#section-3.1
* @see https://www.rfc-editor.org/rfc/rfc2104#section-3
* @see \Cose\Tests\Key\SymmetricKeyValidatorTest
*/
final class SymmetricKeyValidator
{
/**
* The output length of SHA-256, in bytes: the shortest key RFC 2104, section 3 does not discourage for HS256 and
* HS256/64, and the smallest of the three lengths the MAC algorithms of this library use.
*
* Cose\Algorithm\Mac\Hmac::minimumKeyLength() gives the value that matches a given algorithm (32, 48 or 64).
*/
public const MINIMUM_KEY_LENGTH = 32;
private function __construct(
private readonly int $minimumKeyLength
) {
if ($minimumKeyLength < 1) {
throw new InvalidArgumentException('The minimum key length shall be a positive integer');
}
}
public static function create(int $minimumKeyLength = self::MINIMUM_KEY_LENGTH): self
{
return new self($minimumKeyLength);
}
/**
* Returns the length of the key value, in bytes.
*
* @throws InvalidArgumentException when the key is not a usable symmetric key
*/
public static function keyLength(Key $key): int
{
return strlen(self::keyValue($key));
}
/**
* The constraints every MAC algorithm of this library applies on its own: a symmetric key whose `k` is present,
* is a byte string and is not empty. None of them depends on a policy - a `k` that is not a byte string is
* outside RFC 9053, section 7.3, and an empty key makes every tag computable by anyone.
*
* @throws InvalidArgumentException when the key does not satisfy the constraints
*/
public static function checkKeyValue(Key $key): void
{
self::keyValue($key);
}
/**
* @throws InvalidArgumentException when the key does not satisfy the constraints
*/
public function check(Key $key): void
{
$keyLength = strlen(self::keyValue($key));
if ($keyLength < $this->minimumKeyLength) {
throw new InvalidArgumentException(sprintf(
'The key is %d bytes long; at least %d bytes are required',
$keyLength,
$this->minimumKeyLength
));
}
}
public function isValid(Key $key): bool
{
try {
$this->check($key);
} catch (Throwable) {
return false;
}
return true;
}
/**
* @throws InvalidArgumentException when the key does not satisfy the constraints
*/
private static function keyValue(Key $key): string
{
if ($key->type() !== Key::TYPE_OCT && $key->type() !== Key::TYPE_NAME_OCT) {
throw new InvalidArgumentException('Invalid key. Must be of type symmetric');
}
if (! $key->has(SymmetricKey::DATA_K)) {
throw new InvalidArgumentException('Invalid key. The value of the key is missing');
}
$k = $key->get(SymmetricKey::DATA_K);
if (! is_string($k)) {
throw new InvalidArgumentException(
'Invalid key. The value of the key must be a byte string (CBOR objects shall be normalized first)'
);
}
if ($k === '') {
throw new InvalidArgumentException('Invalid key. The value of the key is empty');
}
return $k;
}
}