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,10 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm;
interface Algorithm
{
public static function identifier(): int;
}

View file

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm;
use Cose\Key\Key;
/**
* An algorithm that can enforce the restrictions a COSE key carries: "alg" (label 3) and "key_ops" (label 4), as
* defined by RFC 9052, section 7.1.
*
* Enforcement is opt-in and off by default, so that a key whose labels contradict the operation keeps behaving as it
* did before this library read them. Turn it on with `withKeyRestrictionsEnforced()`, on a single algorithm or on a
* whole `Manager`, to get the behaviour the RFC requires: the operation is refused with an
* `InvalidArgumentException` naming the restriction the key carries.
*
* @see https://www.rfc-editor.org/rfc/rfc9052.html#section-7.1
* @see Key::assertUsableWith()
*/
interface KeyRestrictionAware extends Algorithm
{
/**
* Returns the same algorithm, enforcing - or no longer enforcing - the restrictions of the keys it is given. The
* algorithm this is called on is left untouched.
*/
public function withKeyRestrictionsEnforced(bool $enforce = true): static;
public function enforcesKeyRestrictions(): bool;
}

View file

@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm;
use Cose\Key\Key;
use InvalidArgumentException;
/**
* The opt-in enforcement of the key restrictions of RFC 9052, section 7.1, shared by every algorithm.
*
* @see KeyRestrictionAware
*
* @phpstan-require-implements KeyRestrictionAware
*/
trait KeyRestrictionEnforcement
{
private bool $enforceKeyRestrictions = false;
public function withKeyRestrictionsEnforced(bool $enforce = true): static
{
$clone = clone $this;
$clone->enforceKeyRestrictions = $enforce;
return $clone;
}
public function enforcesKeyRestrictions(): bool
{
return $this->enforceKeyRestrictions;
}
/**
* @param int $operation one of the `Key::OP_*` constants
*
* @throws InvalidArgumentException when enforcement is on and the key is restricted to another algorithm, or
* does not allow the operation
*/
private function checkKeyRestrictions(Key $key, int $operation): void
{
if (! $this->enforceKeyRestrictions) {
return;
}
// static::identifier() is the identifier of the concrete algorithm, so ES256 and ESP256, or EdDSA (-8) and
// the fully-specified Ed25519 (-19), each enforce their own value.
$key->assertUsableWith(static::identifier(), $operation);
}
}

View file

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Mac;
final class HS256 extends Hmac
{
public const ID = 5;
public static function create(bool $acknowledgeShortKey = false): self
{
return new self($acknowledgeShortKey);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): string
{
return 'sha256';
}
protected function getSignatureLength(): int
{
return 256;
}
}

View file

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Mac;
final class HS256Truncated64 extends Hmac
{
public const ID = 4;
public static function create(bool $acknowledgeShortKey = false): self
{
return new self($acknowledgeShortKey);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): string
{
return 'sha256';
}
protected function getSignatureLength(): int
{
return 64;
}
}

View file

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Mac;
final class HS384 extends Hmac
{
public const ID = 6;
public static function create(bool $acknowledgeShortKey = false): self
{
return new self($acknowledgeShortKey);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): string
{
return 'sha384';
}
protected function getSignatureLength(): int
{
return 384;
}
}

View file

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Mac;
final class HS512 extends Hmac
{
public const ID = 7;
public static function create(bool $acknowledgeShortKey = false): self
{
return new self($acknowledgeShortKey);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): string
{
return 'sha512';
}
protected function getSignatureLength(): int
{
return 512;
}
}

View file

@ -0,0 +1,119 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Mac;
use Cose\Algorithm\KeyRestrictionAware;
use Cose\Algorithm\KeyRestrictionEnforcement;
use Cose\Key\Key;
use Cose\Key\SymmetricKey;
use const E_USER_WARNING;
use function hash;
use function hash_hmac;
use InvalidArgumentException;
use function is_string;
use function sprintf;
use function strlen;
use function trigger_error;
/**
* HMAC-based Message Authentication Codes (RFC 9053, section 3.1).
*
* RFC 9053, section 3.1 requires that "implementations creating and validating MAC values MUST validate that the key
* type, key length, and algorithm are correct and appropriate for the entities involved", and section 7.3 types the
* key value `k` as a byte string. Accordingly, a key whose `k` is absent, not a PHP string or empty is rejected: none
* of them is ever a legitimate HMAC key, and coercing such a value would silently key the MAC with a constant an
* outsider can guess ("Array", "1", the empty string, …).
*
* The key length is a softer matter. RFC 2104, section 3 states that a key shorter than the output of the hash
* function is "strongly discouraged", and RFC 9053, section 3.1 only makes the hash output size a SHOULD for keys
* that are transported or derived by a recipient algorithm - neither of which this library implements. A shorter key
* is therefore accepted, but it emits an E_USER_WARNING unless the caller explicitly acknowledges the risk by
* creating the algorithm with `acknowledgeShortKey: true`, following the same shape as
* Cose\Algorithm\Signature\RSA\RS1. From v5.0.0 the same call without that acknowledgement will throw an
* InvalidArgumentException instead of warning.
*
* @see https://www.rfc-editor.org/rfc/rfc9053#section-3.1
* @see https://www.rfc-editor.org/rfc/rfc2104#section-3
* @see \Cose\Tests\Algorithm\Mac\HmacTest
*/
abstract class Hmac implements Mac, KeyRestrictionAware
{
use KeyRestrictionEnforcement;
public const SHORT_KEY_MESSAGE = 'The HMAC key is %d bytes long, shorter than the %d-byte hash output (RFC 2104, section 3). Create the algorithm with "acknowledgeShortKey: true" to acknowledge it; as of v5.0.0 this will throw.';
public function __construct(
private readonly bool $acknowledgeShortKey = false
) {
}
public function hash(string $data, Key $key): string
{
// RFC 9053, section 3.1: "If the 'key_ops' field is present, it MUST include 'MAC create' when creating an
// HMAC authentication tag."
return $this->compute($data, $this->checKey($key, Key::OP_MAC_CREATE));
}
public function verify(string $data, Key $key, string $signature): bool
{
// ... and it MUST include 'MAC verify' when verifying one, so the two operations cannot share a code path.
return hash_equals($this->compute($data, $this->checKey($key, Key::OP_MAC_VERIFY)), $signature);
}
/**
* The length, in bytes, of the output of the underlying hash function: the shortest key RFC 2104, section 3 does
* not discourage for this algorithm.
*/
public function minimumKeyLength(): int
{
return strlen(hash($this->getHashAlgorithm(), '', true));
}
abstract protected function getHashAlgorithm(): string;
abstract protected function getSignatureLength(): int;
private function compute(string $data, string $k): string
{
$signature = hash_hmac($this->getHashAlgorithm(), $data, $k, true);
return substr($signature, 0, intdiv($this->getSignatureLength(), 8));
}
/**
* @param int $operation the Key::OP_* constant of the operation the key is about to be used for
*
* @throws InvalidArgumentException when the key cannot be used with this algorithm
*/
private function checKey(Key $key, int $operation): 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');
}
$minimumKeyLength = $this->minimumKeyLength();
if (strlen($k) < $minimumKeyLength && ! $this->acknowledgeShortKey) {
trigger_error(sprintf(self::SHORT_KEY_MESSAGE, strlen($k), $minimumKeyLength), E_USER_WARNING);
}
$this->checkKeyRestrictions($key, $operation);
return $k;
}
}

View file

@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Mac;
use Cose\Algorithm\Algorithm;
use Cose\Key\Key;
use InvalidArgumentException;
interface Mac extends Algorithm
{
/**
* Computes the authentication tag of the data, the "MAC create" operation of RFC 9052, section 7.1, Table 5.
*
* @throws InvalidArgumentException when the key cannot be used with this algorithm (wrong key type, missing key
* value, or - when the algorithm enforces them, see KeyRestrictionAware - an
* "alg" or a "key_ops" that forbids creating a tag with it)
*/
public function hash(string $data, Key $key): string;
/**
* Verifies an authentication tag, the "MAC verify" operation of RFC 9052, section 7.1, Table 5. It is a distinct
* operation from the one above: a key may be allowed to perform one and not the other.
*
* @throws InvalidArgumentException when the key cannot be used with this algorithm, as above
*/
public function verify(string $data, Key $key, string $signature): bool;
}

View file

@ -0,0 +1,110 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm;
use function array_key_exists;
use const E_USER_WARNING;
use InvalidArgumentException;
use function sprintf;
use function trigger_error;
/**
* @see \Cose\Tests\Algorithm\ManagerTest
*/
final class Manager
{
/**
* @var array<int, Algorithm>
*/
private array $algorithms = [];
public static function create(): self
{
return new self();
}
/**
* Registers algorithms, each under the identifier it declares.
*
* A later registration for an identifier that is already taken replaces the earlier one. When the replacement is
* an instance of another class, that is a misconfiguration rather than an intent: nothing in the Algorithm
* contract reserves an identifier, list() keeps reporting one entry, and the verifier that ends up answering for
* the identifier is decided by registration order alone - which, for the Symfony bundle, is decided by the
* service container. Such a replacement therefore emits an E_USER_WARNING; as of v5.0.0 it will throw an
* InvalidArgumentException, and an explicit replace() will be the way to override a registration on purpose.
*
* Re-registering the same class stays silent, so that a container that autoconfigures the same algorithm twice
* keeps working.
*/
public function add(Algorithm ...$algorithms): self
{
foreach ($algorithms as $algorithm) {
$identifier = $algorithm::identifier();
$registered = $this->algorithms[$identifier] ?? null;
if ($registered !== null && $registered::class !== $algorithm::class) {
trigger_error(sprintf(
'The algorithm identifier %d is already registered with "%s" and is being replaced by "%s". As of v5.0.0, this will throw an exception.',
$identifier,
$registered::class,
$algorithm::class
), E_USER_WARNING);
}
$this->algorithms[$identifier] = $algorithm;
}
return $this;
}
/**
* @return iterable<int>
*/
public function list(): iterable
{
yield from array_keys($this->algorithms);
}
/**
* @return iterable<int, Algorithm>
*/
public function all(): iterable
{
yield from $this->algorithms;
}
/**
* Returns the same set of algorithms, each enforcing - or no longer enforcing - the "alg" and "key_ops"
* restrictions of the keys it is given, as RFC 9052, section 7.1 requires. Algorithms that cannot enforce them
* are carried over unchanged. This manager is left untouched.
*
* @see KeyRestrictionAware
*/
public function withKeyRestrictionsEnforced(bool $enforce = true): self
{
$manager = self::create();
foreach ($this->algorithms as $algorithm) {
$manager->add(
$algorithm instanceof KeyRestrictionAware
? $algorithm->withKeyRestrictionsEnforced($enforce)
: $algorithm
);
}
return $manager;
}
public function has(int $identifier): bool
{
return array_key_exists($identifier, $this->algorithms);
}
public function get(int $identifier): Algorithm
{
if (! $this->has($identifier)) {
throw new InvalidArgumentException('Unsupported algorithm');
}
return $this->algorithms[$identifier];
}
}

View file

@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm;
use function array_key_exists;
use const E_USER_WARNING;
use InvalidArgumentException;
use function sprintf;
use function trigger_error;
/**
* @see \Cose\Tests\Algorithm\ManagerFactoryTest
*/
final class ManagerFactory
{
/**
* @var array<string, Algorithm>
*/
private array $algorithms = [];
public static function create(): self
{
return new self();
}
/**
* Registers an algorithm under an alias.
*
* A later registration for an alias that is already taken replaces the earlier one. When the replacement is an
* instance of another class, that is a misconfiguration rather than an intent, so it emits an E_USER_WARNING; as
* of v5.0.0 it will throw an InvalidArgumentException. Re-registering the same class under the same alias stays
* silent.
*
* Two aliases may legitimately point at the same algorithm, but two aliases whose algorithms share an identifier
* collide as soon as generate() is given both: the Manager it builds keeps only one of them, and warns about the
* replacement.
*/
public function add(string $alias, Algorithm $algorithm): self
{
$registered = $this->algorithms[$alias] ?? null;
if ($registered !== null && $registered::class !== $algorithm::class) {
trigger_error(sprintf(
'The alias "%s" is already registered with "%s" and is being replaced by "%s". As of v5.0.0, this will throw an exception.',
$alias,
$registered::class,
$algorithm::class
), E_USER_WARNING);
}
$this->algorithms[$alias] = $algorithm;
return $this;
}
/**
* @return string[]
*/
public function list(): iterable
{
yield from array_keys($this->algorithms);
}
/**
* @return Algorithm[]
*/
public function all(): iterable
{
yield from $this->algorithms;
}
public function generate(string ...$aliases): Manager
{
$manager = Manager::create();
foreach ($aliases as $alias) {
if (! array_key_exists($alias, $this->algorithms)) {
throw new InvalidArgumentException(sprintf('The algorithm with alias "%s" is not supported', $alias));
}
$manager->add($this->algorithms[$alias]);
}
return $manager;
}
}

View file

@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature;
use Cose\Algorithm\Manager;
use Cose\Key\Key;
use Cose\Key\PublicKeyLoader;
use InvalidArgumentException;
use function sprintf;
/**
* Verifies a signature made by the public key of an X.509 certificate, with the algorithm a COSE identifier names.
*
* WebAuthn Level 3 sections 8.2 to 8.4 ask a relying party to verify a packed (x5c), TPM or android-key attestation
* statement "with the algorithm specified in alg", against the key of the attestation certificate. The obvious route,
* openssl_verify() with Algorithms::getOpensslAlgorithmFor(), only reaches the algorithms an OPENSSL_ALGO_* digest can
* describe - ECDSA and RSASSA-PKCS1-v1_5 - because that digest implies PKCS #1 v1.5 padding; ES256K is missing from
* the map altogether, and RSASSA-PSS, EdDSA, Ed25519 and Ed448 cannot be expressed by it at all.
*
* This class takes the other route: the certificate's key becomes a Cose\Key\Key and the Signature class registered
* for the identifier verifies with it. Three consequences are worth stating.
*
* First, the set of acceptable algorithms is the Manager the operator built, not a constant of this library: an
* identifier that was never registered is refused, so `alg`, which comes from the wire, cannot select a verifier the
* operator did not choose. RS1 in particular is only reachable when the operator registered an RS1 instance, which
* they can only build by acknowledging what SHA-1 is.
*
* Second, every policy a registered algorithm carries applies unchanged, because it is that very instance which
* verifies: the minimum modulus length an RSA algorithm was created with (RsaKeyPolicy, RFC 8230 section 6.1) is the
* one enforced against the key of the certificate. Nothing here overrides it, and nothing has to be configured twice.
*
* Third, verify() is as total as the Signature contract is: it returns false for every signature the algorithm
* rejects, and throws an InvalidArgumentException when the certificate, the identifier or the key type make the
* verification impossible to even attempt.
*
* @see https://www.w3.org/TR/webauthn-3/#sctn-packed-attestation
* @see \Cose\Tests\Algorithm\Signature\CertificateSignatureVerifierTest
*/
final class CertificateSignatureVerifier
{
private function __construct(
private readonly Manager $manager
) {
}
public static function create(Manager $manager): self
{
return new self($manager);
}
/**
* @param string $certificate a PEM or DER encoded X.509 certificate
*
* @throws InvalidArgumentException when the certificate cannot be read, when no signature algorithm is
* registered for the identifier, or when the key of the certificate cannot be used with that algorithm
*/
public function verify(int $algorithmIdentifier, string $certificate, string $data, string $signature): bool
{
return $this->verifyWithKey(
$algorithmIdentifier,
PublicKeyLoader::fromCertificate($certificate),
$data,
$signature
);
}
/**
* The same verification against a bare SubjectPublicKeyInfo (RFC 5280, section 4.1.2.7), PEM or DER encoded, for
* the callers that already hold the key rather than the certificate carrying it.
*
* @throws InvalidArgumentException see verify()
*/
public function verifySubjectPublicKeyInfo(
int $algorithmIdentifier,
string $subjectPublicKeyInfo,
string $data,
string $signature
): bool {
return $this->verifyWithKey(
$algorithmIdentifier,
PublicKeyLoader::fromSubjectPublicKeyInfo($subjectPublicKeyInfo),
$data,
$signature
);
}
private function verifyWithKey(int $algorithmIdentifier, Key $key, string $data, string $signature): bool
{
$algorithm = $this->manager->get($algorithmIdentifier);
if (! $algorithm instanceof Signature) {
throw new InvalidArgumentException(sprintf(
'The algorithm identifier %d is not registered with a signature algorithm',
$algorithmIdentifier
));
}
return $algorithm->verify($data, $key, $signature);
}
}

View file

@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\ECDSA;
use Cose\Algorithm\KeyRestrictionAware;
use Cose\Algorithm\KeyRestrictionEnforcement;
use Cose\Algorithm\Signature\OpenSslError;
use Cose\Algorithm\Signature\Signature;
use Cose\Key\Ec2Key;
use Cose\Key\Key;
use InvalidArgumentException;
use function openssl_pkey_get_private;
use function openssl_pkey_get_public;
use function openssl_sign;
use function openssl_verify;
use function strlen;
use Throwable;
/**
* @see \Cose\Tests\Algorithm\Signature\ECDSA\ECDSATest
*/
abstract class ECDSA implements Signature, KeyRestrictionAware
{
use KeyRestrictionEnforcement;
public function sign(string $data, Key $key): string
{
$key = $this->handleKey($key, Key::OP_SIGN);
if (! $key->isPrivate()) {
throw new InvalidArgumentException('The key is not private.');
}
$privateKey = openssl_pkey_get_private($key->asPEM());
if ($privateKey === false) {
throw new InvalidArgumentException('Unable to load the EC private key');
}
OpenSslError::clear();
// openssl_sign() reports failure with a boolean and never throws: an unusable key would otherwise leave
// $signature null and raise a TypeError inside ECSignature::fromAsn1().
if (! openssl_sign($data, $signature, $privateKey, $this->getHashAlgorithm())) {
throw new InvalidArgumentException('Unable to sign the data: ' . OpenSslError::lastMessage());
}
return ECSignature::fromAsn1($signature, $this->getSignaturePartLength());
}
public function verify(string $data, Key $key, string $signature): bool
{
$key = $this->handleKey($key, Key::OP_VERIFY);
$length = $this->getSignaturePartLength();
// A signature that does not hold exactly the two coordinates of this curve is an invalid signature, not a
// caller error: webauthn-lib hands the bytes of an assertion straight to verify().
if (strlen($signature) !== $length) {
return false;
}
try {
$signature = ECSignature::toAsn1($signature, $length);
} catch (InvalidArgumentException) {
// A well-formed but invalid signature (e.g. R = 0) is a verification failure, not an error.
return false;
}
// The key is loaded before use: openssl_verify() would raise an E_WARNING for key material OpenSSL cannot
// coerce into a public key, e.g. a point that is not on the named curve.
$publicKey = openssl_pkey_get_public($key->toPublic()->asPEM());
if ($publicKey === false) {
return false;
}
return openssl_verify($data, $signature, $publicKey, $this->getHashAlgorithm()) === 1;
}
abstract protected function getCurve(): int;
abstract protected function getHashAlgorithm(): int;
abstract protected function getSignaturePartLength(): int;
private function handleKey(Key $key, int $operation): Ec2Key
{
$this->checkKeyRestrictions($key, $operation);
try {
$key = Ec2Key::create($key->getData());
} catch (InvalidArgumentException $e) {
throw $e;
} catch (Throwable $e) {
// A last resort: key material comes from the wire, and every rejection of it has to reach the caller as
// the exception type this library documents, never as a TypeError or an Error.
throw new InvalidArgumentException('Invalid EC2 key', 0, $e);
}
// RFC 9053 section 7.1 lets a key name its curve instead of numbering it, so the two are compared through
// the registry value rather than through whichever of the two forms the key happens to carry.
if ($key->curveId() !== $this->getCurve()) {
throw new InvalidArgumentException('This key cannot be used with this algorithm');
}
return $key;
}
}

View file

@ -0,0 +1,218 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\ECDSA;
use function bin2hex;
use function hex2bin;
use function hexdec;
use InvalidArgumentException;
use function is_string;
use function sprintf;
use function str_pad;
use const STR_PAD_LEFT;
use function strlen;
use function substr;
/**
* Converts between the COSE signature format (`I2OSP(R, n) | I2OSP(S, n)`, RFC 9053 §2.1) and the DER structure
* `Ecdsa-Sig-Value ::= SEQUENCE { r INTEGER, s INTEGER }` (RFC 3279 §2.2.3) that OpenSSL consumes.
*
* The encoder emits DER as required by X.690 §10.1 and the decoder only accepts DER: every encoding OpenSSL
* refuses (indefinite or non-minimal lengths, negative or non-minimal integers, trailing data) is rejected here.
*
* @internal
*
* @see \Cose\Tests\Algorithm\Signature\ECDSA\ECSignatureTest
*/
final class ECSignature
{
private const ASN1_SEQUENCE = '30';
private const ASN1_INTEGER = '02';
private const ASN1_LENGTH_2BYTES = '81';
private const ASN1_BIG_INTEGER_LIMIT = '7f';
private const ASN1_NEGATIVE_INTEGER = '00';
private const BYTE_SIZE = 2;
public static function toAsn1(string $signature, int $length): string
{
$signature = bin2hex($signature);
if (self::octetLength($signature) !== $length) {
throw new InvalidArgumentException('Invalid signature length.');
}
$pointR = self::preparePositiveInteger(substr($signature, 0, $length));
$pointS = self::preparePositiveInteger(substr($signature, $length));
if ($pointR === '' || $pointS === '') {
// R = 0 or S = 0 is never a valid ECDSA signature (SEC 1 v2 §4.1.4 step 1) and would be encoded
// as an INTEGER without content octets, which X.690 §8.3.1 forbids.
throw new InvalidArgumentException('Invalid signature. R and S must be positive integers.');
}
$lengthR = self::octetLength($pointR);
$lengthS = self::octetLength($pointS);
$totalLength = $lengthR + $lengthS + self::BYTE_SIZE + self::BYTE_SIZE;
$der = hex2bin(
self::ASN1_SEQUENCE . self::encodeAsn1Length($totalLength)
. self::ASN1_INTEGER . self::encodeAsn1Length($lengthR) . $pointR
. self::ASN1_INTEGER . self::encodeAsn1Length($lengthS) . $pointS
);
if (! is_string($der)) {
throw new InvalidArgumentException('Unable to encode the signature.');
}
return $der;
}
public static function fromAsn1(string $signature, int $length): string
{
$message = bin2hex($signature);
$position = 0;
if (self::readAsn1Content($message, $position, self::BYTE_SIZE) !== self::ASN1_SEQUENCE) {
throw new InvalidArgumentException('Invalid data. Should start with a sequence.');
}
$sequenceLength = self::readAsn1Length($message, $position);
if ($sequenceLength * self::BYTE_SIZE !== strlen($message) - $position) {
// X.690 §8.1.3: the length octets cover exactly the contents octets; no trailing data is allowed.
throw new InvalidArgumentException('Invalid data. Sequence length mismatch.');
}
$pointR = self::readAsn1Integer($message, $position, $length);
$pointS = self::readAsn1Integer($message, $position, $length);
$raw = hex2bin(str_pad($pointR, $length, '0', STR_PAD_LEFT) . str_pad($pointS, $length, '0', STR_PAD_LEFT));
if (! is_string($raw)) {
throw new InvalidArgumentException('Unable to decode the signature.');
}
return $raw;
}
private static function octetLength(string $data): int
{
return intdiv(strlen($data), self::BYTE_SIZE);
}
/**
* X.690 §8.1.3.4, §8.1.3.5 and §10.1: short form below 128 octets, minimal long form above. The largest
* `Ecdsa-Sig-Value` contents on the supported curves is 138 octets (P-521), so the `82` form is never needed.
*/
private static function encodeAsn1Length(int $length): string
{
if ($length < 0x80) {
return sprintf('%02x', $length);
}
if ($length <= 0xFF) {
return self::ASN1_LENGTH_2BYTES . sprintf('%02x', $length);
}
throw new InvalidArgumentException('Invalid signature. The length is too large.');
}
private static function preparePositiveInteger(string $data): string
{
if (substr($data, 0, self::BYTE_SIZE) > self::ASN1_BIG_INTEGER_LIMIT) {
return self::ASN1_NEGATIVE_INTEGER . $data;
}
while (
str_starts_with($data, self::ASN1_NEGATIVE_INTEGER)
&& substr($data, 2, self::BYTE_SIZE) <= self::ASN1_BIG_INTEGER_LIMIT
) {
$data = substr($data, 2);
}
return $data;
}
private static function readAsn1Content(string $message, int &$position, int $length): string
{
$content = substr($message, $position, $length);
$position += $length;
return $content;
}
private static function readAsn1Length(string $message, int &$position): int
{
$firstOctet = self::readAsn1Content($message, $position, self::BYTE_SIZE);
if (strlen($firstOctet) !== self::BYTE_SIZE) {
throw new InvalidArgumentException('Invalid data. Truncated length.');
}
$first = (int) hexdec($firstOctet);
if ($first < 0x80) {
// Short form (X.690 §8.1.3.4).
return $first;
}
if ($first === 0x81) {
$secondOctet = self::readAsn1Content($message, $position, self::BYTE_SIZE);
if (strlen($secondOctet) !== self::BYTE_SIZE) {
throw new InvalidArgumentException('Invalid data. Truncated length.');
}
$value = (int) hexdec($secondOctet);
if ($value < 0x80) {
// X.690 §10.1: the length is encoded in the minimum number of octets.
throw new InvalidArgumentException('Invalid data. Non-minimal length encoding.');
}
return $value;
}
// 0x80 is the indefinite form, forbidden in DER (X.690 §8.1.3.6 and §10.1); 0x82 and above are never
// needed for an Ecdsa-Sig-Value on the supported curves.
throw new InvalidArgumentException('Invalid data. Unsupported length encoding.');
}
private static function readAsn1Integer(string $message, int &$position, int $length): string
{
if (self::readAsn1Content($message, $position, self::BYTE_SIZE) !== self::ASN1_INTEGER) {
throw new InvalidArgumentException('Invalid data. Should contain an integer.');
}
$contentLength = self::readAsn1Length($message, $position);
if ($contentLength === 0) {
// X.690 §8.3.1: the contents octets consist of one or more octets.
throw new InvalidArgumentException('Invalid data. Empty integer.');
}
$content = self::readAsn1Content($message, $position, $contentLength * self::BYTE_SIZE);
if (strlen($content) !== $contentLength * self::BYTE_SIZE) {
throw new InvalidArgumentException('Invalid data. Truncated integer.');
}
$first = (int) hexdec(substr($content, 0, self::BYTE_SIZE));
if ($first >= 0x80) {
// X.690 §8.3.3: the contents octets are a two's complement number, so this integer is negative.
throw new InvalidArgumentException('Invalid data. Negative integer.');
}
if ($first === 0) {
if ($contentLength === 1) {
// SEC 1 v2 §4.1.4 step 1: R and S must lie in [1, n-1].
throw new InvalidArgumentException('Invalid signature. R and S must be positive integers.');
}
if ((int) hexdec(substr($content, self::BYTE_SIZE, self::BYTE_SIZE)) < 0x80) {
// X.690 §8.3.2 b): the first nine bits must not all be zero.
throw new InvalidArgumentException('Invalid data. Non-minimal integer.');
}
// Drop the single sign octet the encoding is allowed to carry.
$content = substr($content, self::BYTE_SIZE);
}
if (strlen($content) > $length) {
throw new InvalidArgumentException('Invalid data. The integer is too large for the curve.');
}
return $content;
}
}

View file

@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA256;
final class ES256 extends ECDSA
{
public const ID = -7;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA256;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_P256;
}
protected function getSignaturePartLength(): int
{
return 64;
}
}

View file

@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA256;
final class ES256K extends ECDSA
{
public const ID = -47;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA256;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_P256K;
}
protected function getSignaturePartLength(): int
{
return 64;
}
}

View file

@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA384;
final class ES384 extends ECDSA
{
public const ID = -35;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA384;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_P384;
}
protected function getSignaturePartLength(): int
{
return 96;
}
}

View file

@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA512;
final class ES512 extends ECDSA
{
public const ID = -36;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA512;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_P521;
}
protected function getSignaturePartLength(): int
{
return 132;
}
}

View file

@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\EdDSA;
final class Ed25519 extends EdDSA
{
public const ID = -8;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
}

View file

@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\EdDSA;
use Cose\Key\Key;
use const E_USER_WARNING;
use function hash;
use function trigger_error;
/**
* Pure Ed25519 over the SHA-256 digest of the payload.
*
* This construction is defined by no specification. It is neither the EdDSA of RFC 8032, section 5.1 - which signs
* the message itself - nor Ed25519ph of the same section, whose challenge covers a "dom2" prefix this class does not
* add. RFC 9053, section 2.2 is explicit that "for use with COSE, only the pure EdDSA version is used", and RFC 8032,
* section 8.5 warns that prehashing "makes the functions greatly more vulnerable to weaknesses in hash functions
* used. These variants SHOULD NOT be used."
*
* Worse, the identifier it carries is not free: IANA has since assigned -260 to WalnutDSA (RFC 9021, section 6.1), so
* a COSE object signed here is read as WalnutDSA by every conforming implementation, and a genuine WalnutDSA object
* is routed to this class. No WebAuthn authenticator emits -260, so the only deployments this construction can serve
* are those that use it on both ends. The fully-specified EdDSA identifiers are
* {@see \Cose\Algorithm\Signature\FullySpecified\Ed25519} (-19) and
* {@see \Cose\Algorithm\Signature\FullySpecified\Ed448} (-53).
*
* Because of that, creating this algorithm emits an E_USER_WARNING unless the caller explicitly acknowledges what it
* is by passing `acknowledgeNonStandardAlgorithm: true`. From v5.0.0 the same call without that acknowledgement will
* throw an InvalidArgumentException instead of warning, and the identifier will move out of the range IANA
* administers.
*
* @see https://www.rfc-editor.org/rfc/rfc9021#section-6.1
* @see https://www.rfc-editor.org/rfc/rfc8032#section-8.5
* @see \Cose\Tests\Algorithm\Signature\EdDSA\PrehashedEdDSATest
*/
final class Ed256 extends EdDSA
{
public const ID = -260;
public const NON_STANDARD_ALGORITHM_MESSAGE = 'The algorithm Ed256 (-260) signs the SHA-256 digest of the payload with pure Ed25519, a construction no specification defines, and its identifier is assigned by IANA to WalnutDSA. If you know what you are doing, create it with "acknowledgeNonStandardAlgorithm: true"; as of v5.0.0, omitting that acknowledgement will throw an exception.';
public function __construct(bool $acknowledgeNonStandardAlgorithm = false)
{
parent::__construct();
if (! $acknowledgeNonStandardAlgorithm) {
trigger_error(self::NON_STANDARD_ALGORITHM_MESSAGE, E_USER_WARNING);
}
}
public static function create(bool $acknowledgeNonStandardAlgorithm = false): self
{
return new self($acknowledgeNonStandardAlgorithm);
}
public static function identifier(): int
{
return self::ID;
}
public function sign(string $data, Key $key): string
{
$hashedData = hash('sha256', $data, true);
return parent::sign($hashedData, $key);
}
public function verify(string $data, Key $key, string $signature): bool
{
$hashedData = hash('sha256', $data, true);
return parent::verify($hashedData, $key, $signature);
}
}

View file

@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\EdDSA;
use Cose\Key\Key;
use const E_USER_WARNING;
use function hash;
use function trigger_error;
/**
* Pure Ed25519 over the SHA-512 digest of the payload.
*
* Despite its name this is not EdDSA with Curve448, and it rejects an Ed448 key: the signature is computed by
* {@see EdDSA}, whose curve check accepts Ed25519 only. EdDSA with Curve448, RFC 8032 section 5.2, is
* {@see \Cose\Algorithm\Signature\FullySpecified\Ed448} (-53).
*
* The construction is defined by no specification. It is neither the EdDSA of RFC 8032, section 5.1 - which signs the
* message itself - nor Ed25519ph of the same section, whose challenge covers a "dom2" prefix this class does not add.
* RFC 9053, section 2.2 is explicit that "for use with COSE, only the pure EdDSA version is used", and RFC 8032,
* section 8.5 warns that prehashing "makes the functions greatly more vulnerable to weaknesses in hash functions
* used. These variants SHOULD NOT be used."
*
* Worse, the identifier it carries is not free: IANA has since assigned -261 to TurboSHAKE128 (RFC 9861, section 6),
* so a COSE object signed here is read as TurboSHAKE128 by every conforming implementation, and a genuine
* TurboSHAKE128 object is routed to this class. No WebAuthn authenticator emits -261, so the only deployments this
* construction can serve are those that use it on both ends.
*
* Because of that, creating this algorithm emits an E_USER_WARNING unless the caller explicitly acknowledges what it
* is by passing `acknowledgeNonStandardAlgorithm: true`. From v5.0.0 the same call without that acknowledgement will
* throw an InvalidArgumentException instead of warning, and the identifier will move out of the range IANA
* administers.
*
* @see https://www.rfc-editor.org/rfc/rfc9861#section-6
* @see https://www.rfc-editor.org/rfc/rfc8032#section-8.5
* @see \Cose\Tests\Algorithm\Signature\EdDSA\PrehashedEdDSATest
*/
final class Ed512 extends EdDSA
{
public const ID = -261;
public const NON_STANDARD_ALGORITHM_MESSAGE = 'The algorithm Ed512 (-261) signs the SHA-512 digest of the payload with pure Ed25519, a construction no specification defines, and its identifier is assigned by IANA to TurboSHAKE128. If you know what you are doing, create it with "acknowledgeNonStandardAlgorithm: true"; as of v5.0.0, omitting that acknowledgement will throw an exception.';
public function __construct(bool $acknowledgeNonStandardAlgorithm = false)
{
parent::__construct();
if (! $acknowledgeNonStandardAlgorithm) {
trigger_error(self::NON_STANDARD_ALGORITHM_MESSAGE, E_USER_WARNING);
}
}
public static function create(bool $acknowledgeNonStandardAlgorithm = false): self
{
return new self($acknowledgeNonStandardAlgorithm);
}
public static function identifier(): int
{
return self::ID;
}
public function sign(string $data, Key $key): string
{
$hashedData = hash('sha512', $data, true);
return parent::sign($hashedData, $key);
}
public function verify(string $data, Key $key, string $signature): bool
{
$hashedData = hash('sha512', $data, true);
return parent::verify($hashedData, $key, $signature);
}
}

View file

@ -0,0 +1,124 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\EdDSA;
use Cose\Algorithm\KeyRestrictionAware;
use Cose\Algorithm\KeyRestrictionEnforcement;
use Cose\Algorithm\Signature\Signature;
use Cose\Algorithms;
use Cose\Key\Key;
use Cose\Key\OkpKey;
use function extension_loaded;
use function hash_equals;
use InvalidArgumentException;
use RuntimeException;
use function sodium_crypto_sign_detached;
use function sodium_crypto_sign_publickey;
use function sodium_crypto_sign_secretkey;
use function sodium_crypto_sign_seed_keypair;
use function sodium_crypto_sign_verify_detached;
use function sodium_memzero;
use SodiumException;
use Throwable;
/**
* @see \Cose\Tests\Algorithm\Signature\EdDSA\EdDSATest
*/
class EdDSA implements Signature, KeyRestrictionAware
{
use KeyRestrictionEnforcement;
public function __construct()
{
if (! self::isSupported()) {
throw new RuntimeException(
'The EdDSA algorithms require the Sodium extension, which is not loaded.'
);
}
}
/**
* Ed25519 is computed with the sodium extension. It ships with PHP and is enabled by default, but a build can
* leave it out; the algorithm is then unusable, and verify() would report every signature as invalid instead of
* saying why, because it turns any error into a verification outcome. Availability is therefore settled once,
* when the algorithm is instantiated.
*/
public static function isSupported(): bool
{
return extension_loaded('sodium');
}
public function sign(string $data, Key $key): string
{
$key = $this->handleKey($key, Key::OP_SIGN);
if (! $key->isPrivate()) {
throw new InvalidArgumentException('The key is not private.');
}
if ($key->curveId() !== OkpKey::CURVE_ED25519) {
throw new InvalidArgumentException('Unsupported curve');
}
// RFC 8032 section 5.1.5 defines the public key A as a function of the private seed, and section 5.1.6 puts
// that very A into the challenge k = SHA-512(R || A || M). Sodium uses the public half of the secret key
// verbatim, so handing it a caller-supplied "x" would let two signatures of the same message under two
// different halves share their nonce R and disclose the private scalar. A is therefore always re-derived
// from "d" here, and a stored "x" is only ever compared against it.
$keyPair = sodium_crypto_sign_seed_keypair($key->d());
$secret = sodium_crypto_sign_secretkey($keyPair);
$public = sodium_crypto_sign_publickey($keyPair);
sodium_memzero($keyPair);
$x = $key->has(OkpKey::DATA_X) ? $key->x() : null;
if ($x !== null && ! hash_equals($public, $x)) {
sodium_memzero($secret);
throw new InvalidArgumentException(
'Invalid key: the public key "x" does not correspond to the private key "d".'
);
}
try {
return sodium_crypto_sign_detached($data, $secret);
} finally {
sodium_memzero($secret);
}
}
public function verify(string $data, Key $key, string $signature): bool
{
$key = $this->handleKey($key, Key::OP_VERIFY);
if ($key->curveId() !== OkpKey::CURVE_ED25519) {
throw new InvalidArgumentException('Unsupported curve');
}
// Sodium reports a signature or a public key whose size is not the one Ed25519 defines with a
// SodiumException; that is an invalid signature, not an error. Anything else — a missing extension above
// all — is a platform fault and must not be reported as a verification outcome.
try {
return sodium_crypto_sign_verify_detached($signature, $data, $key->x());
} catch (SodiumException) {
return false;
}
}
public static function identifier(): int
{
return Algorithms::COSE_ALGORITHM_EDDSA;
}
private function handleKey(Key $key, int $operation): OkpKey
{
$this->checkKeyRestrictions($key, $operation);
try {
return OkpKey::create($key->getData());
} catch (InvalidArgumentException $e) {
throw $e;
} catch (Throwable $e) {
// A last resort: key material comes from the wire, and every rejection of it has to reach the caller as
// the exception type this library documents, never as a TypeError or an Error.
throw new InvalidArgumentException('Invalid OKP key', 0, $e);
}
}
}

View file

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\FullySpecified;
use Cose\Algorithm\Signature\ECDSA\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA256;
/**
* ECDSA using the brainpoolP256r1 curve and SHA-256.
*
* @see https://www.rfc-editor.org/rfc/rfc9864.html#section-2.1
*/
final class ESB256 extends ECDSA
{
public const ID = -265;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA256;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_BP256;
}
protected function getSignaturePartLength(): int
{
return 64;
}
}

View file

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\FullySpecified;
use Cose\Algorithm\Signature\ECDSA\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA384;
/**
* ECDSA using the brainpoolP320r1 curve and SHA-384.
*
* @see https://www.rfc-editor.org/rfc/rfc9864.html#section-2.1
*/
final class ESB320 extends ECDSA
{
public const ID = -266;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA384;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_BP320;
}
protected function getSignaturePartLength(): int
{
return 80;
}
}

View file

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\FullySpecified;
use Cose\Algorithm\Signature\ECDSA\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA384;
/**
* ECDSA using the brainpoolP384r1 curve and SHA-384.
*
* @see https://www.rfc-editor.org/rfc/rfc9864.html#section-2.1
*/
final class ESB384 extends ECDSA
{
public const ID = -267;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA384;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_BP384;
}
protected function getSignaturePartLength(): int
{
return 96;
}
}

View file

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\FullySpecified;
use Cose\Algorithm\Signature\ECDSA\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA512;
/**
* ECDSA using the brainpoolP512r1 curve and SHA-512.
*
* @see https://www.rfc-editor.org/rfc/rfc9864.html#section-2.1
*/
final class ESB512 extends ECDSA
{
public const ID = -268;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA512;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_BP512;
}
protected function getSignaturePartLength(): int
{
return 128;
}
}

View file

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\FullySpecified;
use Cose\Algorithm\Signature\ECDSA\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA256;
/**
* ECDSA using the P-256 curve and SHA-256.
*
* @see https://www.rfc-editor.org/rfc/rfc9864.html#section-2.1
*/
final class ESP256 extends ECDSA
{
public const ID = -9;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA256;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_P256;
}
protected function getSignaturePartLength(): int
{
return 64;
}
}

View file

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\FullySpecified;
use Cose\Algorithm\Signature\ECDSA\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA384;
/**
* ECDSA using the P-384 curve and SHA-384.
*
* @see https://www.rfc-editor.org/rfc/rfc9864.html#section-2.1
*/
final class ESP384 extends ECDSA
{
public const ID = -51;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA384;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_P384;
}
protected function getSignaturePartLength(): int
{
return 96;
}
}

View file

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\FullySpecified;
use Cose\Algorithm\Signature\ECDSA\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA512;
/**
* ECDSA using the P-521 curve and SHA-512.
*
* @see https://www.rfc-editor.org/rfc/rfc9864.html#section-2.1
*/
final class ESP512 extends ECDSA
{
public const ID = -52;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA512;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_P521;
}
protected function getSignaturePartLength(): int
{
return 132;
}
}

View file

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\FullySpecified;
use Cose\Algorithm\Signature\EdDSA\EdDSA;
/**
* EdDSA using the Ed25519 parameter set of RFC 8032, section 5.1.
*
* This is the fully-specified counterpart of the polymorphic EdDSA identifier (-8). The cryptography is identical;
* only the algorithm identifier differs.
*
* @see https://www.rfc-editor.org/rfc/rfc9864.html#section-2.2
*/
final class Ed25519 extends EdDSA
{
public const ID = -19;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
}

View file

@ -0,0 +1,119 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\FullySpecified;
use Cose\Algorithm\KeyRestrictionAware;
use Cose\Algorithm\KeyRestrictionEnforcement;
use Cose\Algorithm\Signature\OpenSslError;
use Cose\Algorithm\Signature\Signature;
use Cose\Key\Key;
use Cose\Key\OkpKey;
use InvalidArgumentException;
use function openssl_pkey_get_private;
use function openssl_pkey_get_public;
use function openssl_sign;
use function openssl_verify;
use const PHP_VERSION_ID;
use RuntimeException;
use Throwable;
/**
* EdDSA using the Ed448 parameter set of RFC 8032, section 5.2.
*
* Unlike Ed25519, Ed448 is not covered by the sodium extension; it is computed through OpenSSL, which PHP only wires
* up for Edwards curves as of PHP 8.4. Call `isSupported()` before use when the platform is not known in advance.
*
* @see https://www.rfc-editor.org/rfc/rfc9864.html#section-2.2
*/
final class Ed448 implements Signature, KeyRestrictionAware
{
use KeyRestrictionEnforcement;
public const ID = -53;
/**
* EdDSA is a one-shot signature scheme: the message is not hashed beforehand, which OpenSSL expects to be
* expressed by an empty digest algorithm.
*/
private const NO_DIGEST = 0;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
/**
* Ed448 requires PHP 8.4 or later: earlier versions reject the digest-less signature OpenSSL needs for Edwards
* curves.
*/
public static function isSupported(): bool
{
return PHP_VERSION_ID >= 80400;
}
public function sign(string $data, Key $key): string
{
$key = $this->handleKey($key, Key::OP_SIGN);
if (! $key->isPrivate()) {
throw new InvalidArgumentException('The key is not private.');
}
$privateKey = openssl_pkey_get_private($key->asPEM());
if ($privateKey === false) {
throw new InvalidArgumentException('Unable to load the Ed448 private key');
}
OpenSslError::clear();
if (! openssl_sign($data, $signature, $privateKey, self::NO_DIGEST)) {
throw new InvalidArgumentException('Unable to sign the data: ' . OpenSslError::lastMessage());
}
return $signature;
}
public function verify(string $data, Key $key, string $signature): bool
{
$key = $this->handleKey($key, Key::OP_VERIFY);
// RFC 8032 section 5.2.7: a public key that cannot be decoded as a point makes the signature invalid; it is
// a verification outcome, not an error.
$publicKey = openssl_pkey_get_public($key->toPublic()->asPEM());
if ($publicKey === false) {
return false;
}
return openssl_verify($data, $signature, $publicKey, self::NO_DIGEST) === 1;
}
private function handleKey(Key $key, int $operation): OkpKey
{
if (! self::isSupported()) {
throw new RuntimeException(
'The Ed448 algorithm requires PHP 8.4 or later, as earlier versions cannot sign or verify with Edwards curves through OpenSSL.'
);
}
$this->checkKeyRestrictions($key, $operation);
try {
$key = OkpKey::create($key->getData());
} catch (InvalidArgumentException $e) {
throw $e;
} catch (Throwable $e) {
// A last resort: key material comes from the wire, and every rejection of it has to reach the caller as
// the exception type this library documents, never as a TypeError or an Error.
throw new InvalidArgumentException('Invalid OKP key', 0, $e);
}
if ($key->curveId() !== OkpKey::CURVE_ED448) {
throw new InvalidArgumentException('This key cannot be used with this algorithm');
}
return $key;
}
}

View file

@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature;
use function openssl_error_string;
/**
* Reads the OpenSSL error queue so that a failed signature operation can say why it failed.
*
* @internal
*/
final class OpenSslError
{
/**
* Empties the queue, so that lastMessage() reports the errors of the next operation only. The queue is
* process-wide and is not cleared by successful calls.
*/
public static function clear(): void
{
while (openssl_error_string() !== false) {
// Nothing to do: the call itself pops one entry off the queue.
}
}
/**
* Returns the most recent message of the queue, emptying it.
*/
public static function lastMessage(): string
{
$message = false;
while (($entry = openssl_error_string()) !== false) {
$message = $entry;
}
return $message === false ? 'unknown OpenSSL error' : $message;
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\RSA;
use Cose\Hash;
use Cose\Key\RsaKeyValidator;
final class PS256 extends PSSRSA
{
public const ID = -37;
public static function create(?RsaKeyValidator $keyValidator = null): self
{
return new self($keyValidator);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): Hash
{
return Hash::sha256();
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\RSA;
use Cose\Hash;
use Cose\Key\RsaKeyValidator;
final class PS384 extends PSSRSA
{
public const ID = -38;
public static function create(?RsaKeyValidator $keyValidator = null): self
{
return new self($keyValidator);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): Hash
{
return Hash::sha384();
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\RSA;
use Cose\Hash;
use Cose\Key\RsaKeyValidator;
final class PS512 extends PSSRSA
{
public const ID = -39;
public static function create(?RsaKeyValidator $keyValidator = null): self
{
return new self($keyValidator);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): Hash
{
return Hash::sha512();
}
}

View file

@ -0,0 +1,538 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\RSA;
use Brick\Math\Exception\MathException;
use function chr;
use Cose\Algorithm\KeyRestrictionAware;
use Cose\Algorithm\KeyRestrictionEnforcement;
use Cose\Algorithm\Signature\Signature;
use Cose\BigInteger;
use Cose\Hash;
use Cose\Key\Key;
use Cose\Key\RsaKey;
use Cose\Key\RsaKeyValidator;
use function hash_equals;
use function intdiv;
use InvalidArgumentException;
use function is_string;
use function ltrim;
use function openssl_error_string;
use const OPENSSL_NO_PADDING;
use function openssl_pkey_get_public;
use function openssl_private_encrypt;
use function openssl_public_decrypt;
use function ord;
use function pack;
use function random_bytes;
use RuntimeException;
use function str_pad;
use const STR_PAD_LEFT;
use function str_repeat;
use function strcmp;
use function strlen;
use function substr;
use Throwable;
/**
* RSASSA-PSS as defined by RFC 8017, section 8.1.
*
* The length of the key is bounded before it is used. RFC 8017, section 3.1 places no upper bound on the modulus nor
* on the public exponent, and the primitives of section 5.2 are modular exponentiations whose cost is proportional to
* the size of both - which a verifier takes from whoever produced the message. RFC 8230, section 6.1 asks for the
* bound: "It is highly recommended that checks on the key length be done before starting a cryptographic operation."
* The same section requires "a key size of 2048 bits or larger": that bound is applied by RsaKeyPolicy, with the
* validator this algorithm was created with or, by default, with RsaKeyValidator::create().
*
* @see https://www.rfc-editor.org/rfc/rfc8017#section-8.1
* @see https://www.rfc-editor.org/rfc/rfc8230#section-6.1
*
* @internal
*/
abstract class PSSRSA implements Signature, KeyRestrictionAware
{
use KeyRestrictionEnforcement;
use RsaKeyPolicy;
public function __construct(?RsaKeyValidator $keyValidator = null)
{
$this->initializeKeyValidator($keyValidator);
}
public function sign(string $data, Key $key): string
{
$key = $this->handleKey($key, Key::OP_SIGN);
RsaKeyValidator::checkPublicParameters($key);
RsaKeyValidator::checkLengthBounds($key);
$this->checkKeyPolicy($key);
if (! $key->isPrivate()) {
throw new InvalidArgumentException('The key is not private.');
}
// RFC 8017, section 3.1: modBits is the length in bits of the modulus and k its length in octets. Both are
// derived from the integer value of n, not from the number of octets used to encode it.
$modBits = RsaKeyValidator::modulusLength($key);
$k = intdiv($modBits + 7, 8);
// RFC 8017, section 8.1.1, steps 1 and 2.
$em = $this->encodeEMSAPSS($data, $modBits - 1, $this->getHashAlgorithm());
$signature = $this->rsasp1($key, BigInteger::createFromBinaryString($em));
return $this->convertIntegerToOctetString($signature, $k);
}
public function verify(string $data, Key $key, string $signature): bool
{
// RFC 8017, section 8.1.2: the verification operation uses the public key (n, e) only.
$key = $this->handleKey($key, Key::OP_VERIFY)
->toPublic();
try {
// Section 8.1.2 applies RSAVP1 under the assumption that the public key is valid (section 3.1). Nothing
// downstream re-establishes it, and with e = 1 the exponentiation below is the identity map: the EMSA-PSS
// encoding of any message, which anyone can build, would then be accepted as its signature. Section 3.1
// bounds neither parameter either, and the cost of the exponentiation grows with the size of both. A key
// that cannot be verified with, or that is too large to compute with, is reported as an invalid
// signature, per the contract of Signature::verify().
RsaKeyValidator::checkPublicParameters($key);
RsaKeyValidator::checkLengthBounds($key);
// A key below the bound the caller asked for is a key it declared it does not verify with, which is an
// invalid signature rather than an error here too. The implicit default only warns.
$this->checkKeyPolicy($key);
} catch (InvalidArgumentException) {
return false;
}
$modBits = RsaKeyValidator::modulusLength($key);
$k = intdiv($modBits + 7, 8);
// RFC 8017, section 8.1.2, step 1: "If the length of the signature S is not k octets, output 'invalid
// signature' and stop."
if (strlen($signature) !== $k) {
return false;
}
// Step 2.b: "If RSAVP1 output 'signature representative out of range', output 'invalid signature' and stop."
if (self::compareMagnitudes($signature, $key->n()) >= 0) {
return false;
}
$em = $this->rsavp1WithOpenSSL($key, $signature);
if ($em === null) {
return false;
}
// RFC 8017, section 8.1.2, step 2.c: emLen = ceil((modBits - 1) / 8). "If I2OSP outputs 'integer too large',
// output 'invalid signature' and stop." OpenSSL returns k octets, one more than emLen when the modulus is
// byte aligned, and the octets it drops have to be zero for the integer to fit.
$emLen = intdiv($modBits - 1 + 7, 8);
if ($emLen < $k) {
if (ltrim(substr($em, 0, $k - $emLen), "\0") !== '') {
return false;
}
$em = substr($em, $k - $emLen);
}
return $this->verifyEMSAPSS($data, $em, $modBits - 1, $this->getHashAlgorithm());
}
/**
* Exponentiate with or without Chinese Remainder Theorem. Operation with primes 'p' and 'q' is appox. 2x faster.
*
* The operation is selected from the key: RSASP1 (RFC 8017, section 5.2.1) for a private key, RSAVP1 (section
* 5.2.2) for a public one.
*
* @throws InvalidArgumentException when the public parameters of the key are not those of a valid RSA key, or
* when it is rejected by the validator this algorithm was created with
*/
public function exponentiate(RsaKey $key, BigInteger $c): BigInteger
{
RsaKeyValidator::checkPublicParameters($key);
RsaKeyValidator::checkLengthBounds($key);
$this->checkKeyPolicy($key);
return $key->isPrivate() ? $this->rsasp1($key, $c) : $this->rsavp1($key, $c);
}
abstract protected function getHashAlgorithm(): Hash;
private function handleKey(Key $key, int $operation): RsaKey
{
$this->checkKeyRestrictions($key, $operation);
return RsaKey::create($key->getData());
}
/**
* RSAVP1 (RFC 8017, section 5.2.2).
*
* Only exponentiate() reaches this method: verify() applies the primitive to the octet strings themselves. The
* in-process exponentiation is kept here as a fallback so that a key OpenSSL declines still gets an answer, which
* is the behaviour this method has always had.
*/
private function rsavp1(RsaKey $key, BigInteger $s): BigInteger
{
$n = BigInteger::createFromBinaryString($key->n());
if ($s->compare(BigInteger::createFromDecimal(0)) < 0 || $s->compare($n) >= 0) {
throw new RuntimeException('Signature representative out of range');
}
$k = intdiv(RsaKeyValidator::modulusLength($key) + 7, 8);
$m = $this->rsavp1WithOpenSSL($key, $this->convertIntegerToOctetString($s, $k));
return $m === null
? $s->modPow(BigInteger::createFromBinaryString($key->e()), $n)
: BigInteger::createFromBinaryString($m);
}
/**
* RSAVP1 computed by OpenSSL, on the octet strings themselves.
*
* The public operation is a modular exponentiation, and brick/math computes it in PHP whenever neither ext-gmp
* nor ext-bcmath is loaded - the configuration of the stock php and php-fpm images. That costs seconds of CPU per
* verification even for a 2048 bit key, and grows with the square of the modulus up to the largest one RFC 8230
* asks implementations to accept: a verifier takes its key from whoever produced the message, so the work it is
* asked to do must not depend on an extension being installed. ext-openssl is a hard requirement of this package,
* and RSASP1 already goes through it.
*
* Returns null when OpenSSL will not use the key, which for a verifier is an invalid signature: RFC 8017, section
* 8.1.2 is defined for a valid public key, and a key OpenSSL rejects is not one.
*
* @param string $s the signature representative, exactly k octets long and below the modulus
*/
private function rsavp1WithOpenSSL(RsaKey $key, string $s): ?string
{
try {
// The key is loaded before use so that key material OpenSSL cannot decode yields null instead of an
// E_WARNING raised from inside openssl_public_decrypt().
$publicKey = openssl_pkey_get_public($key->toPublic()->asPem());
if ($publicKey === false) {
$this->clearOpenSSLErrors();
return null;
}
$computed = openssl_public_decrypt($s, $m, $publicKey, OPENSSL_NO_PADDING);
} catch (Throwable) {
$this->clearOpenSSLErrors();
return null;
}
if (! $computed || ! is_string($m)) {
$this->clearOpenSSLErrors();
return null;
}
return $m;
}
/**
* Compares two non-negative integers given as big-endian octet strings: the longer one, once the leading zero
* octets are gone, is the larger, and equal lengths are decided octet by octet. Comparing the values rather than
* the strings would mean converting them, which is the very base conversion this class avoids.
*/
private static function compareMagnitudes(string $left, string $right): int
{
$left = ltrim($left, "\0");
$right = ltrim($right, "\0");
$byLength = strlen($left) <=> strlen($right);
return $byLength === 0 ? strcmp($left, $right) : $byLength;
}
/**
* RSASP1 (RFC 8017, section 5.2.1).
*/
private function rsasp1(RsaKey $key, BigInteger $m): BigInteger
{
$n = BigInteger::createFromBinaryString($key->n());
if ($m->compare(BigInteger::createFromDecimal(0)) < 0 || $m->compare($n) >= 0) {
throw new RuntimeException('Message representative out of range');
}
$e = BigInteger::createFromBinaryString($key->e());
$hasCrtParameters = $key->hasPrimes() && $key->hasExponents() && $key->hasCoefficient();
if ($hasCrtParameters && ! $key->has(RsaKey::DATA_OTHER)) {
// A two-prime key with a complete CRT quintuple is the only shape RsaKey::asPem() can express, and the
// only one OpenSSL can therefore compute. Its exponentiation is blinded and runs in constant time, which
// neither gmp_powm() nor bcpowmod() nor the native brick/math loop does.
$this->checkCrtParameters($key, $n);
$signature = $this->rsasp1WithOpenSSL($key, $m);
} else {
// Multi-prime keys (RFC 8230, section 4) and (n, e, d) keys have no PEM representation, so they keep the
// in-process exponentiation. Blinding the base hides it from an attacker timing the operation or watching
// the cache while it runs; it does not make the exponentiation itself constant-time.
[$blindingFactor, $unblindingFactor] = $this->blindingFactors($n, $e);
$blinded = $m->multiply($blindingFactor)
->mod($n)
;
$signature = $hasCrtParameters
? $this->rsasp1WithCrt($key, $blinded)
// RFC 8017, section 5.2.1, step 2.a: first form (n, d).
: $blinded->modPow(BigInteger::createFromBinaryString($key->d()), $n);
$signature = $signature->multiply($unblindingFactor)
->mod($n)
;
}
// A wrong CRT result must never leave this class: it would be a silently invalid signature and, on faulty
// hardware, a private key recovery oracle. OpenSSL applies the very same check.
if ($signature->modPow($e, $n)->compare($m) !== 0) {
throw new RuntimeException(
'Inconsistent RSA private key: the CRT parameters do not describe the modulus'
);
}
return $signature;
}
/**
* RSASP1 computed by OpenSSL: base blinding and BN_mod_exp_mont_consttime on the private exponent, plus its own
* check of the CRT result against the public operation.
*/
private function rsasp1WithOpenSSL(RsaKey $key, BigInteger $m): BigInteger
{
$k = intdiv(RsaKeyValidator::modulusLength($key) + 7, 8);
try {
$computed = openssl_private_encrypt(
$this->convertIntegerToOctetString($m, $k),
$signature,
$key->asPem(),
OPENSSL_NO_PADDING
);
} catch (Throwable $throwable) {
$this->clearOpenSSLErrors();
throw new RuntimeException('Unable to compute the RSA signature primitive', 0, $throwable);
}
if (! $computed || ! is_string($signature)) {
$this->clearOpenSSLErrors();
throw new RuntimeException('Unable to compute the RSA signature primitive');
}
return BigInteger::createFromBinaryString($signature);
}
/**
* OpenSSL repairs a key whose CRT parameters do not describe the modulus instead of reporting it, so the
* consistency of the quintuple is established before the exponentiation rather than after it.
*/
private function checkCrtParameters(RsaKey $key, BigInteger $n): void
{
$one = BigInteger::createFromDecimal(1);
[$pS, $qS] = $key->primes();
[$dPS, $dQS] = $key->exponents();
$p = BigInteger::createFromBinaryString($pS);
$q = BigInteger::createFromBinaryString($qS);
$e = BigInteger::createFromBinaryString($key->e());
// A prime of 0 or 1 would make the reductions below meaningless, and n = p * q rules it out on its own only
// for the other factor.
$this->assertCrtParameter($p->compare($one) > 0 && $q->compare($one) > 0);
$this->assertCrtParameter($this->isEqual($p->multiply($q), $n));
// e * dP = 1 mod (p - 1), e * dQ = 1 mod (q - 1) and q * qInv = 1 mod p (RFC 8017, section 3.2).
$this->assertCrtParameter(
$this->isEqual($e->multiply(BigInteger::createFromBinaryString($dPS))->mod($p->subtract($one)), $one)
);
$this->assertCrtParameter(
$this->isEqual($e->multiply(BigInteger::createFromBinaryString($dQS))->mod($q->subtract($one)), $one)
);
$this->assertCrtParameter(
$this->isEqual($q->multiply(BigInteger::createFromBinaryString($key->QInv()))->mod($p), $one)
);
}
private function assertCrtParameter(bool $isConsistent): void
{
if (! $isConsistent) {
throw new RuntimeException(
'Inconsistent RSA private key: the CRT parameters do not describe the modulus'
);
}
}
private function isEqual(BigInteger $left, BigInteger $right): bool
{
return $left->compare($right) === 0;
}
/**
* A random r coprime with n, returned as the pair (r^e mod n, r^-1 mod n): multiplying the message representative
* by the first before the exponentiation and the result by the second after it leaves the signature unchanged,
* while the value actually exponentiated is unpredictable.
*
* @return array{BigInteger, BigInteger}
*/
private function blindingFactors(BigInteger $n, BigInteger $e): array
{
$two = BigInteger::createFromDecimal(2);
// Eight bytes beyond the modulus keep the bias of the reduction below negligible.
$length = strlen($n->toBytes()) + 8;
$upperBound = $n->subtract(BigInteger::createFromDecimal(3));
while (true) {
$r = BigInteger::createFromBinaryString(random_bytes($length))
->mod($upperBound)
->add($two)
;
try {
// Drawing an r sharing a factor with n means having factored n, so this never loops in practice.
$unblindingFactor = $r->modInverse($n);
} catch (MathException) {
continue;
}
return [$r->modPow($e, $n), $unblindingFactor];
}
}
/**
* RFC 8017, section 5.2.1, step 2.b.
*/
private function rsasp1WithCrt(RsaKey $key, BigInteger $m): BigInteger
{
[$pS, $qS] = $key->primes();
[$dPS, $dQS] = $key->exponents();
$p = BigInteger::createFromBinaryString($pS);
$q = BigInteger::createFromBinaryString($qS);
// Steps 2.b.1, 2.b.3 and 2.b.4.
$s1 = $m->modPow(BigInteger::createFromBinaryString($dPS), $p);
$s2 = $m->modPow(BigInteger::createFromBinaryString($dQS), $q);
$h = $s1->subtract($s2)
->multiply(BigInteger::createFromBinaryString($key->QInv()))
->mod($p)
;
$signature = $s2->add($h->multiply($q));
if (! $key->has(RsaKey::DATA_OTHER)) {
return $signature;
}
// Steps 2.b.2 and 2.b.5, for the third to u-th primes of a multi-prime key (RFC 8230, section 4).
$r = $p->multiply($q);
foreach ($key->other() as $primeInfo) {
$rI = BigInteger::createFromBinaryString($primeInfo[RsaKey::DATA_RI]);
$sI = $m->modPow(BigInteger::createFromBinaryString($primeInfo[RsaKey::DATA_DI]), $rI);
$h = $sI->subtract($signature)
->multiply(BigInteger::createFromBinaryString($primeInfo[RsaKey::DATA_TI]))
->mod($rI)
;
$signature = $signature->add($r->multiply($h));
$r = $r->multiply($rI);
}
return $signature;
}
/**
* Drains the OpenSSL error queue so that a failure here is not reported by an unrelated later call.
*/
private function clearOpenSSLErrors(): void
{
while (openssl_error_string() !== false) {
}
}
private function convertIntegerToOctetString(BigInteger $x, int $xLen): string
{
$xB = $x->toBytes();
if (strlen($xB) > $xLen) {
throw new RuntimeException('Unable to convert the integer');
}
return str_pad($xB, $xLen, chr(0), STR_PAD_LEFT);
}
/**
* MGF1.
*/
private function getMGF1(string $mgfSeed, int $maskLen, Hash $mgfHash): string
{
$t = '';
$count = intdiv($maskLen + $mgfHash->getLength() - 1, $mgfHash->getLength());
for ($i = 0; $i < $count; ++$i) {
$c = pack('N', $i);
$t .= $mgfHash->hash($mgfSeed . $c);
}
return substr($t, 0, $maskLen);
}
/**
* The mask of the leftmost 8emLen - emBits bits of the leftmost octet of maskedDB (RFC 8017, section 9.1.1, step
* 11 and section 9.1.2, steps 6 and 9). It is 0x00 when the encoded message is byte aligned and nothing has to be
* cleared.
*/
private function leftmostBitsMask(int $emBits): string
{
$bitsToClear = 8 * intdiv($emBits + 7, 8) - $emBits;
return chr((0xFF << (8 - $bitsToClear)) & 0xFF);
}
/**
* EMSA-PSS-ENCODE (RFC 8017, section 9.1.1).
*/
private function encodeEMSAPSS(string $message, int $emBits, Hash $hash): string
{
$emLen = intdiv($emBits + 7, 8);
$hLen = $hash->getLength();
$sLen = $hLen;
$mHash = $hash->hash($message);
if ($emLen < $hLen + $sLen + 2) {
throw new RuntimeException(
'Encoding error: the modulus is too short for this hash and salt length'
);
}
$salt = random_bytes($sLen);
$m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
$h = $hash->hash($m2);
$ps = str_repeat(chr(0), $emLen - $sLen - $hLen - 2);
$db = $ps . chr(1) . $salt;
$dbMask = $this->getMGF1($h, $emLen - $hLen - 1, $hash);
$maskedDB = $db ^ $dbMask;
$maskedDB[0] = ~$this->leftmostBitsMask($emBits) & $maskedDB[0];
return $maskedDB . $h . chr(0xBC);
}
/**
* EMSA-PSS-VERIFY (RFC 8017, section 9.1.2).
*/
private function verifyEMSAPSS(string $m, string $em, int $emBits, Hash $hash): bool
{
$emLen = intdiv($emBits + 7, 8);
$hLen = $hash->getLength();
$sLen = $hLen;
$mHash = $hash->hash($m);
// Every check below is a step whose failure RFC 8017, section 9.1.2 defines as "output 'inconsistent' and
// stop", i.e. an invalid signature rather than an error.
// Step 3: the modulus is too short for this hash and salt length.
if ($emLen < $hLen + $sLen + 2) {
return false;
}
// Step 4: the trailer field is not 0xBC.
if ($em[strlen($em) - 1] !== chr(0xBC)) {
return false;
}
$maskedDB = substr($em, 0, -$hLen - 1);
$h = substr($em, -$hLen - 1, $hLen);
$mask = $this->leftmostBitsMask($emBits);
// Step 6: the leftmost bits of maskedDB are not zero.
if (($maskedDB[0] & $mask) !== chr(0)) {
return false;
}
$dbMask = $this->getMGF1($h, $emLen - $hLen - 1, $hash/* MGF */);
$db = $maskedDB ^ $dbMask;
$db[0] = ~$mask & $db[0];
$temp = $emLen - $hLen - $sLen - 2;
// Step 10: the padding string is not zero, or the separator octet is not 0x01.
if (! str_starts_with($db, str_repeat(chr(0), $temp))) {
return false;
}
if (ord($db[$temp]) !== 1) {
return false;
}
$salt = substr($db, $temp + 1); // should be $sLen long
$m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
$h2 = $hash->hash($m2);
return hash_equals($h, $h2);
}
}

View file

@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\RSA;
use Cose\Key\RsaKeyValidator;
use const E_USER_WARNING;
use const OPENSSL_ALGO_SHA1;
use function trigger_error;
/**
* RSASSA-PKCS1-v1_5 using SHA-1.
*
* SHA-1 is no longer acceptable for digital signatures: NIST has recommended against generating signatures with it
* since the end of 2010 and forbidden its use by U.S. federal agencies for sensitive but unclassified information
* since the end of 2013 (see RFC 6194 and NIST SP 800-131A). The algorithm is kept for the legacy authenticators
* that still rely on it.
*
* Because of that, creating this algorithm emits an E_USER_WARNING unless the caller explicitly acknowledges the risk
* by passing `acknowledgeInsecureAlgorithm: true`. From v5.0.0 the same call without that acknowledgement will throw
* an InvalidArgumentException instead of warning.
*
* @see https://datatracker.ietf.org/doc/html/rfc6194
*/
final class RS1 extends RSA
{
public const ID = -65535;
public const INSECURE_ALGORITHM_MESSAGE = 'The algorithm RS1 (RSASSA-PKCS1-v1_5 with SHA-1) is not secure and shall only be used to verify signatures produced by legacy authenticators. If you know what you are doing, create it with "acknowledgeInsecureAlgorithm: true"; as of v5.0.0, omitting that acknowledgement will throw an exception.';
public function __construct(bool $acknowledgeInsecureAlgorithm = false, ?RsaKeyValidator $keyValidator = null)
{
parent::__construct($keyValidator);
if (! $acknowledgeInsecureAlgorithm) {
trigger_error(self::INSECURE_ALGORITHM_MESSAGE, E_USER_WARNING);
}
}
public static function create(
bool $acknowledgeInsecureAlgorithm = false,
?RsaKeyValidator $keyValidator = null
): self {
return new self($acknowledgeInsecureAlgorithm, $keyValidator);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA1;
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\RSA;
use Cose\Key\RsaKeyValidator;
use const OPENSSL_ALGO_SHA256;
final class RS256 extends RSA
{
public const ID = -257;
public static function create(?RsaKeyValidator $keyValidator = null): self
{
return new self($keyValidator);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA256;
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\RSA;
use Cose\Key\RsaKeyValidator;
use const OPENSSL_ALGO_SHA384;
final class RS384 extends RSA
{
public const ID = -258;
public static function create(?RsaKeyValidator $keyValidator = null): self
{
return new self($keyValidator);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA384;
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\RSA;
use Cose\Key\RsaKeyValidator;
use const OPENSSL_ALGO_SHA512;
final class RS512 extends RSA
{
public const ID = -259;
public static function create(?RsaKeyValidator $keyValidator = null): self
{
return new self($keyValidator);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA512;
}
}

View file

@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\RSA;
use Cose\Algorithm\KeyRestrictionAware;
use Cose\Algorithm\KeyRestrictionEnforcement;
use Cose\Algorithm\Signature\OpenSslError;
use Cose\Algorithm\Signature\Signature;
use Cose\Key\Key;
use Cose\Key\RsaKey;
use Cose\Key\RsaKeyValidator;
use InvalidArgumentException;
use function openssl_pkey_get_private;
use function openssl_pkey_get_public;
use function openssl_sign;
use function openssl_verify;
/**
* RSASSA-PKCS1-v1_5 as defined by RFC 8017, section 8.2.
*
* Section 8.2.2 applies RSAVP1 under the assumption that the public key is valid, i.e. that its exponent is an odd
* integer between 3 and n - 1 (section 3.1). openssl_verify() does not re-check it: with e = 1 the public operation
* is the identity map, so the EMSA-PKCS1-v1_5 encoding of a message - public data anyone can compute - would be
* accepted as a signature of that message under an attacker chosen key. Every key is therefore checked here.
*
* Its length is bounded too, before it is used. RFC 8230, section 6.1 asks for it - "It is highly recommended that
* checks on the key length be done before starting a cryptographic operation" - because the work an RSA operation
* costs grows with the size of the key it is given, and a verifier takes that key from whoever produced the message.
* The same section requires "a key size of 2048 bits or larger": that bound is applied by RsaKeyPolicy, with the
* validator this algorithm was created with or, by default, with RsaKeyValidator::create().
*
* @see https://www.rfc-editor.org/rfc/rfc8017#section-8.2
* @see \Cose\Tests\Algorithm\Signature\RSA\RSATest
*/
abstract class RSA implements Signature, KeyRestrictionAware
{
use KeyRestrictionEnforcement;
use RsaKeyPolicy;
public function __construct(?RsaKeyValidator $keyValidator = null)
{
$this->initializeKeyValidator($keyValidator);
}
public function sign(string $data, Key $key): string
{
$key = $this->handleKey($key, Key::OP_SIGN);
RsaKeyValidator::checkPublicParameters($key);
RsaKeyValidator::checkLengthBounds($key);
$this->checkKeyPolicy($key);
if (! $key->isPrivate()) {
throw new InvalidArgumentException('The key is not private.');
}
$privateKey = openssl_pkey_get_private($key->asPem());
if ($privateKey === false) {
throw new InvalidArgumentException('Unable to load the RSA private key');
}
OpenSslError::clear();
// openssl_sign() reports failure with a boolean and never throws: a modulus too short for the digest would
// otherwise leave $signature null and raise a TypeError on the way out.
if (! openssl_sign($data, $signature, $privateKey, $this->getHashAlgorithm())) {
throw new InvalidArgumentException('Unable to sign the data: ' . OpenSslError::lastMessage());
}
return $signature;
}
public function verify(string $data, Key $key, string $signature): bool
{
$key = $this->handleKey($key, Key::OP_VERIFY);
try {
RsaKeyValidator::checkPublicParameters($key);
RsaKeyValidator::checkLengthBounds($key);
// A key below the bound the caller asked for is a key it declared it does not verify with, which is an
// invalid signature rather than an error here too. The implicit default only warns.
$this->checkKeyPolicy($key);
} catch (InvalidArgumentException) {
// A key too large to compute with, or one that does not satisfy RFC 8017, section 3.1, is key material no
// verification can be performed with: the contract of Signature::verify() reports it as an invalid
// signature, not as an error.
return false;
}
// The key is loaded before use so that key material OpenSSL cannot decode yields false instead of an
// E_WARNING raised from inside openssl_verify().
$publicKey = openssl_pkey_get_public($key->toPublic()->asPem());
if ($publicKey === false) {
return false;
}
return openssl_verify($data, $signature, $publicKey, $this->getHashAlgorithm()) === 1;
}
abstract protected function getHashAlgorithm(): int;
private function handleKey(Key $key, int $operation): RsaKey
{
$this->checkKeyRestrictions($key, $operation);
return RsaKey::create($key->getData());
}
}

View file

@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\RSA;
use Cose\Key\RsaKey;
use Cose\Key\RsaKeyValidator;
use const E_USER_WARNING;
use InvalidArgumentException;
use function sprintf;
use function trigger_error;
/**
* The minimum modulus length every RSA algorithm of this library applies to the keys it is given.
*
* RFC 8230, section 6.1 - to which RFC 8812 defers for the WebAuthn registrations - states that "a key size of 2048
* bits or larger MUST be used with these algorithms" and that "it is highly recommended that checks on the key length
* be done before starting a cryptographic operation". That recommendation is addressed to the component performing
* the operation, which is this library, so RsaKeyValidator::create() is applied by default rather than left to the
* caller.
*
* Legacy authenticators holding 1024 bit keys exist, so the default bound cannot be enforced with an exception
* without breaking them: it emits an E_USER_WARNING in 4.x and will throw as of v5.0.0, following the schedule RS1
* already uses. A caller who has to accept a weaker key says so by handing the algorithm a validator of its own -
* RsaKeyValidator::create(minimumModulusLength: 1024) - which both records the bound actually accepted and applies it
* immediately, with an exception, instead of silencing the check altogether.
*
* Only the *minimum* modulus length goes through here. The public parameter constraints of RFC 8017, section 3.1 and
* the upper bounds on the size of the key are not a policy and are applied unconditionally by the algorithms
* themselves, before this check runs; nothing a validator rejects here has been left unchecked by them.
*
* @see https://www.rfc-editor.org/rfc/rfc8230#section-6.1
*
* @internal
*/
trait RsaKeyPolicy
{
private RsaKeyValidator $keyValidator;
/**
* Whether the validator was chosen by the caller, in which case the bound it carries is enforced with an
* exception, as opposed to the implicit default, which only warns until v5.0.0.
*/
private bool $keyValidatorIsExplicit;
private function initializeKeyValidator(?RsaKeyValidator $keyValidator): void
{
$this->keyValidatorIsExplicit = $keyValidator !== null;
$this->keyValidator = $keyValidator ?? RsaKeyValidator::create();
}
/**
* @throws InvalidArgumentException when the key is rejected by a validator the caller provided
*/
private function checkKeyPolicy(RsaKey $key): void
{
if (! isset($this->keyValidator)) {
// Both abstract classes gained their constructor in 4.8.0: an algorithm extending one of them from
// outside this library and overriding it without calling the parent gets the default rather than an
// error on an uninitialised property.
$this->initializeKeyValidator(null);
}
try {
$this->keyValidator->check($key);
} catch (InvalidArgumentException $exception) {
if ($this->keyValidatorIsExplicit) {
throw $exception;
}
trigger_error(
sprintf(RsaKeyValidator::WEAK_KEY_MESSAGE, $exception->getMessage()),
E_USER_WARNING
);
}
}
}

View file

@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature;
use Cose\Algorithm\Algorithm;
use Cose\Key\Key;
use InvalidArgumentException;
interface Signature extends Algorithm
{
/**
* @throws InvalidArgumentException when the key cannot be used to sign with this algorithm (wrong key type, wrong
* curve, public key, key material the crypto layer refuses, or - when the
* algorithm enforces them, see KeyRestrictionAware - an "alg" or a "key_ops"
* that forbids signing with it)
*/
public function sign(string $data, Key $key): string;
/**
* Verification is total for every condition the underlying specification defines as an "invalid signature"
* outcome: a malformed, truncated, over-long or out-of-range signature, and key material no verification can be
* performed with (an off-curve point, a public key that is not a valid group element, an RSA key whose public
* parameters are not those RFC 8017 defines, …) all yield false.
*
* @throws InvalidArgumentException when $key cannot be used with this algorithm at all, i.e. its key type or its
* curve does not match, or - when the algorithm enforces them, see
* KeyRestrictionAware - its "alg" or its "key_ops" forbids the verification.
* Structurally invalid key components are rejected earlier, by the Key
* constructors.
*/
public function verify(string $data, Key $key, string $signature): bool;
}

View file

@ -0,0 +1,290 @@
<?php
declare(strict_types=1);
namespace Cose;
use function array_key_exists;
use Cose\Algorithm\Signature\RSA\RS1;
use const E_USER_WARNING;
use InvalidArgumentException;
use const OPENSSL_ALGO_SHA1;
use const OPENSSL_ALGO_SHA256;
use const OPENSSL_ALGO_SHA384;
use const OPENSSL_ALGO_SHA512;
use function trigger_error;
/**
* @see https://www.iana.org/assignments/cose/cose.xhtml#algorithms
*/
abstract class Algorithms
{
final public const COSE_ALGORITHM_AES_CCM_64_128_256 = 33;
final public const COSE_ALGORITHM_AES_CCM_64_128_128 = 32;
final public const COSE_ALGORITHM_AES_CCM_16_128_256 = 31;
final public const COSE_ALGORITHM_AES_CCM_16_128_128 = 30;
final public const COSE_ALGORITHM_AES_MAC_256_128 = 26;
final public const COSE_ALGORITHM_AES_MAC_128_128 = 25;
final public const COSE_ALGORITHM_CHACHA20_POLY1305 = 24;
final public const COSE_ALGORITHM_AES_MAC_256_64 = 15;
final public const COSE_ALGORITHM_AES_MAC_128_64 = 14;
final public const COSE_ALGORITHM_AES_CCM_64_64_256 = 13;
final public const COSE_ALGORITHM_AES_CCM_64_64_128 = 12;
final public const COSE_ALGORITHM_AES_CCM_16_64_256 = 11;
final public const COSE_ALGORITHM_AES_CCM_16_64_128 = 10;
final public const COSE_ALGORITHM_HS512 = 7;
final public const COSE_ALGORITHM_HS384 = 6;
final public const COSE_ALGORITHM_HS256 = 5;
final public const COSE_ALGORITHM_HS256_64 = 4;
final public const COSE_ALGORITHM_A256GCM = 3;
final public const COSE_ALGORITHM_A192GCM = 2;
final public const COSE_ALGORITHM_A128GCM = 1;
final public const COSE_ALGORITHM_A128KW = -3;
final public const COSE_ALGORITHM_A192KW = -4;
final public const COSE_ALGORITHM_A256KW = -5;
final public const COSE_ALGORITHM_DIRECT = -6;
final public const COSE_ALGORITHM_ES256 = -7;
/**
* @deprecated since v4.0.6. Please use COSE_ALGORITHM_EDDSA instead. Will be removed in v5.0.0
*/
final public const COSE_ALGORITHM_EdDSA = -8;
final public const COSE_ALGORITHM_EDDSA = -8;
/**
* Ed25519 over a SHA-256 (-260) or SHA-512 (-261) digest of the message. These pre-hash variants are not
* registered anywhere and are not EdDSA identifiers: the IANA COSE Algorithms registry assigns -260 to WalnutDSA
* and -261 to TurboSHAKE128. They are kept for the authenticators that already produce them; new code should use
* COSE_ALGORITHM_ED25519 (-19) or COSE_ALGORITHM_ED448 (-53).
*/
final public const COSE_ALGORITHM_ED256 = -260;
final public const COSE_ALGORITHM_ED512 = -261;
final public const COSE_ALGORITHM_DIRECT_HKDF_SHA_256 = -10;
final public const COSE_ALGORITHM_DIRECT_HKDF_SHA_512 = -11;
final public const COSE_ALGORITHM_DIRECT_HKDF_AES_128 = -12;
final public const COSE_ALGORITHM_DIRECT_HKDF_AES_256 = -13;
final public const COSE_ALGORITHM_ECDH_ES_HKDF_256 = -25;
final public const COSE_ALGORITHM_ECDH_ES_HKDF_512 = -26;
final public const COSE_ALGORITHM_ECDH_SS_HKDF_256 = -27;
final public const COSE_ALGORITHM_ECDH_SS_HKDF_512 = -28;
final public const COSE_ALGORITHM_ECDH_ES_A128KW = -29;
final public const COSE_ALGORITHM_ECDH_ES_A192KW = -30;
final public const COSE_ALGORITHM_ECDH_ES_A256KW = -31;
final public const COSE_ALGORITHM_ECDH_SS_A128KW = -32;
final public const COSE_ALGORITHM_ECDH_SS_A192KW = -33;
final public const COSE_ALGORITHM_ECDH_SS_A256KW = -34;
final public const COSE_ALGORITHM_ES384 = -35;
final public const COSE_ALGORITHM_ES512 = -36;
final public const COSE_ALGORITHM_PS256 = -37;
final public const COSE_ALGORITHM_PS384 = -38;
final public const COSE_ALGORITHM_PS512 = -39;
final public const COSE_ALGORITHM_RSAES_OAEP = -40;
final public const COSE_ALGORITHM_RSAES_OAEP_256 = -41;
final public const COSE_ALGORITHM_RSAES_OAEP_512 = -42;
final public const COSE_ALGORITHM_ES256K = -47;
final public const COSE_ALGORITHM_RS256 = -257;
final public const COSE_ALGORITHM_RS384 = -258;
final public const COSE_ALGORITHM_RS512 = -259;
final public const COSE_ALGORITHM_RS1 = -65535;
/**
* Fully-specified algorithm identifiers: unlike the polymorphic identifiers above, these determine the curve and
* the hash on their own instead of leaving them to the other parameters of the key.
*
* @see https://www.rfc-editor.org/rfc/rfc9864.html
*/
final public const COSE_ALGORITHM_ESP256 = -9;
final public const COSE_ALGORITHM_ESP384 = -51;
final public const COSE_ALGORITHM_ESP512 = -52;
final public const COSE_ALGORITHM_ESB256 = -265;
final public const COSE_ALGORITHM_ESB320 = -266;
final public const COSE_ALGORITHM_ESB384 = -267;
final public const COSE_ALGORITHM_ESB512 = -268;
final public const COSE_ALGORITHM_ED25519 = -19;
final public const COSE_ALGORITHM_ED448 = -53;
/**
* The digest to hand to openssl_sign() / openssl_verify() for the ECDSA and RSASSA-PKCS1-v1_5 algorithms, and
* for those only.
*
* openssl_verify() called with an OPENSSL_ALGO_* digest implies PKCS #1 v1.5 padding, so PS256, PS384 and PS512
* (RSASSA-PSS) are deliberately absent, and so are EdDSA (-8), Ed25519 (-19) and Ed448 (-53), which are one-shot
* schemes that hash the message themselves. Verifying with one of those identifiers goes through the matching
* Cose\Algorithm\Signature\Signature class instead - Cose\Algorithm\Signature\CertificateSignatureVerifier
* does exactly that for a signature made by the key of an X.509 certificate.
*
* @internal this constant bypasses getOpensslAlgorithmFor() and the acknowledgement it requires for RS1; it will
* become private in the next major version
* @var array<int, int>
*/
final public const COSE_ALGORITHM_MAP = [
self::COSE_ALGORITHM_ES256 => OPENSSL_ALGO_SHA256,
self::COSE_ALGORITHM_ES256K => OPENSSL_ALGO_SHA256,
self::COSE_ALGORITHM_ES384 => OPENSSL_ALGO_SHA384,
self::COSE_ALGORITHM_ES512 => OPENSSL_ALGO_SHA512,
self::COSE_ALGORITHM_ESP256 => OPENSSL_ALGO_SHA256,
self::COSE_ALGORITHM_ESP384 => OPENSSL_ALGO_SHA384,
self::COSE_ALGORITHM_ESP512 => OPENSSL_ALGO_SHA512,
self::COSE_ALGORITHM_ESB256 => OPENSSL_ALGO_SHA256,
self::COSE_ALGORITHM_ESB320 => OPENSSL_ALGO_SHA384,
self::COSE_ALGORITHM_ESB384 => OPENSSL_ALGO_SHA384,
self::COSE_ALGORITHM_ESB512 => OPENSSL_ALGO_SHA512,
self::COSE_ALGORITHM_RS256 => OPENSSL_ALGO_SHA256,
self::COSE_ALGORITHM_RS384 => OPENSSL_ALGO_SHA384,
self::COSE_ALGORITHM_RS512 => OPENSSL_ALGO_SHA512,
self::COSE_ALGORITHM_RS1 => OPENSSL_ALGO_SHA1,
];
/**
* The name of the digest each algorithm identifier uses, as hash() spells it.
*
* The EdDSA identifiers (-8, -19, -53) are absent: they name one-shot signature schemes with no separately
* applicable digest.
*
* @internal this constant bypasses getHashAlgorithmFor() and the acknowledgement it requires for RS1; it will
* become private in the next major version
* @var array<int, string>
*/
final public const COSE_HASH_MAP = [
self::COSE_ALGORITHM_ES256K => 'sha256',
self::COSE_ALGORITHM_ES256 => 'sha256',
self::COSE_ALGORITHM_ES384 => 'sha384',
self::COSE_ALGORITHM_ES512 => 'sha512',
self::COSE_ALGORITHM_ESP256 => 'sha256',
self::COSE_ALGORITHM_ESP384 => 'sha384',
self::COSE_ALGORITHM_ESP512 => 'sha512',
self::COSE_ALGORITHM_ESB256 => 'sha256',
self::COSE_ALGORITHM_ESB320 => 'sha384',
self::COSE_ALGORITHM_ESB384 => 'sha384',
self::COSE_ALGORITHM_ESB512 => 'sha512',
self::COSE_ALGORITHM_RS256 => 'sha256',
self::COSE_ALGORITHM_RS384 => 'sha384',
self::COSE_ALGORITHM_RS512 => 'sha512',
self::COSE_ALGORITHM_PS256 => 'sha256',
self::COSE_ALGORITHM_PS384 => 'sha384',
self::COSE_ALGORITHM_PS512 => 'sha512',
self::COSE_ALGORITHM_RS1 => 'sha1',
];
/**
* The digest to hand to openssl_sign() / openssl_verify() for an ECDSA or RSASSA-PKCS1-v1_5 identifier.
*
* @see self::COSE_ALGORITHM_MAP for the identifiers this covers, and for those it deliberately does not
*
* @param bool $acknowledgeInsecureAlgorithm see Cose\Algorithm\Signature\RSA\RS1: SHA-1 is only handed out
* against an explicit acknowledgement, as creating the RS1 algorithm itself is
*
* @throws InvalidArgumentException when the identifier is not one this map describes
*/
public static function getOpensslAlgorithmFor(
int $algorithmIdentifier,
bool $acknowledgeInsecureAlgorithm = false
): int {
if (! array_key_exists($algorithmIdentifier, self::COSE_ALGORITHM_MAP)) {
throw new InvalidArgumentException('The specified algorithm identifier is not supported');
}
self::checkInsecureAlgorithm($algorithmIdentifier, $acknowledgeInsecureAlgorithm);
return self::COSE_ALGORITHM_MAP[$algorithmIdentifier];
}
/**
* The name of the digest an identifier uses, as hash() spells it.
*
* @see self::COSE_HASH_MAP for the identifiers this covers, and for those it deliberately does not
*
* @param bool $acknowledgeInsecureAlgorithm see Cose\Algorithm\Signature\RSA\RS1: SHA-1 is only handed out
* against an explicit acknowledgement, as creating the RS1 algorithm itself is
*
* @throws InvalidArgumentException when the identifier is not one this map describes
*/
public static function getHashAlgorithmFor(
int $algorithmIdentifier,
bool $acknowledgeInsecureAlgorithm = false
): string {
if (! array_key_exists($algorithmIdentifier, self::COSE_HASH_MAP)) {
throw new InvalidArgumentException('The specified algorithm identifier is not supported');
}
self::checkInsecureAlgorithm($algorithmIdentifier, $acknowledgeInsecureAlgorithm);
return self::COSE_HASH_MAP[$algorithmIdentifier];
}
/**
* The RS1 class refuses to be created without an acknowledgement, but the two accessors above expose the very
* same primitive - SHA-1 with PKCS #1 v1.5 padding - without any object ever being built, and their result is
* handed straight to openssl_verify(). The policy therefore has to hold here too, otherwise the operator's
* decision not to register RS1 has no effect on the code paths that go through these maps.
*
* Unlike RS1::__construct(), this fires per verification rather than once at configuration time, which is
* precisely what makes an unacknowledged SHA-1 verification visible in the logs.
*/
private static function checkInsecureAlgorithm(int $algorithmIdentifier, bool $acknowledgeInsecureAlgorithm): void
{
if ($algorithmIdentifier === self::COSE_ALGORITHM_RS1 && ! $acknowledgeInsecureAlgorithm) {
// As of v5.0.0, this will throw an InvalidArgumentException instead of warning.
trigger_error(RS1::INSECURE_ALGORITHM_MESSAGE, E_USER_WARNING);
}
}
}

View file

@ -0,0 +1,123 @@
<?php
declare(strict_types=1);
namespace Cose;
use Brick\Math\BigInteger as BrickBigInteger;
use Brick\Math\Exception\MathException;
use function chr;
use function hex2bin;
use function strlen;
use function unpack;
/**
* @internal
*/
final class BigInteger
{
private function __construct(
private readonly BrickBigInteger $value
) {
}
public static function createFromBinaryString(string $value): self
{
$res = unpack('H*', $value);
/** @var non-empty-string $data */
$data = current($res);
return new self(BrickBigInteger::fromBase($data, 16));
}
public static function createFromDecimal(int $value): self
{
return new self(BrickBigInteger::of($value));
}
/**
* Converts a BigInteger to a binary string.
*/
public function toBytes(): string
{
if ($this->value->isEqualTo(BrickBigInteger::zero())) {
return '';
}
$temp = $this->value->toBase(16);
$temp = 0 !== (strlen($temp) & 1) ? '0' . $temp : $temp;
$temp = hex2bin($temp);
return ltrim($temp, chr(0));
}
/**
* Adds two BigIntegers.
*/
public function add(self $y): self
{
$value = $this->value->plus($y->value);
return new self($value);
}
/**
* Subtracts two BigIntegers.
*/
public function subtract(self $y): self
{
$value = $this->value->minus($y->value);
return new self($value);
}
/**
* Multiplies two BigIntegers.
*/
public function multiply(self $x): self
{
$value = $this->value->multipliedBy($x->value);
return new self($value);
}
/**
* Performs modular exponentiation.
*/
public function modPow(self $e, self $n): self
{
$value = $this->value->modPow($e->value, $n->value);
return new self($value);
}
/**
* Returns the modular multiplicative inverse of this number modulo $m.
*
* @throws MathException if this number is not invertible modulo $m, i.e. if they are not coprime
*/
public function modInverse(self $m): self
{
$value = $this->value->modInverse($m->value);
return new self($value);
}
/**
* Performs modular exponentiation.
*/
public function mod(self $d): self
{
$value = $this->value->mod($d->value);
return new self($value);
}
/**
* Compares two numbers.
*/
public function compare(self $y): int
{
return $this->value->compareTo($y->value);
}
}

View file

@ -0,0 +1,155 @@
<?php
declare(strict_types=1);
namespace Cose\Encryption;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\Decoder;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\OtherObject\OtherObjectManager;
use CBOR\StringStream;
use CBOR\Tag;
use CBOR\Tag\CoseEncrypt0Tag as UpstreamTag;
use CBOR\Tag\TagManager;
use const E_USER_DEPRECATED;
use InvalidArgumentException;
use function sprintf;
use function trigger_error;
/**
* A tagged COSE_Encrypt0 (RFC 9052, CBOR tag 16).
*
* @deprecated since 4.8.0, use \CBOR\Tag\CoseEncrypt0Tag from spomky-labs/cbor-php 3.4.0 or later instead. Will be removed
* in 5.0.0.
*
* The six COSE structures were ported upstream in cbor-php 3.4.0, where they share AbstractCoseTag and are
* registered in the default decoder, so Decoder::create() resolves tag 16 on its own. The replacement accepts what
* this class rejects -- a zero-length protected header, a detached (nil) payload, the indefinite-length encodings --
* and reads every item through the list it carries, so its accessors cannot drift from the bytes it serializes.
*
* What does not move upstream is the RFC 9052 layer above the CBOR shape, and that stays here: {@see \Cose\Structure\CoseHeaders}
* for header labels typed as RFC 9052 section 1.5 defines them, and the Sig_structure, MAC_structure and
* Enc_structure builders that a signature or a MAC is actually computed over. Both work on the upstream classes.
*
* Migrating: the class name changes, and the four-argument create() becomes createFromComponents() -- upstream
* create() takes the whole list instead.
*
* @see https://github.com/web-auth/cose-lib/issues/176
* @see \Cose\Tests\Structure\DeprecatedTagClassesTest
*/
final class CoseEncrypt0Tag extends Tag
{
/**
* A COSE header is a flat map of a handful of parameters whose values nest a couple of levels at most, so the
* decoder built when none is given is bounded far below the cbor-php default of 1000: a protected header crafted
* to nest thousands of levels is rejected instead of being walked.
*/
public const DEFAULT_PROTECTED_HEADER_MAX_DEPTH = 32;
private const TAG_ID = 16;
private readonly ByteStringObject $protectedHeader;
private readonly MapObject $unprotectedHeader;
private readonly ByteStringObject $ciphertext;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
trigger_error(sprintf(
'The class "%s" is deprecated since 4.8.0 and will be removed in 5.0.0. Use "%s" from spomky-labs/cbor-php 3.4.0 or later instead.',
self::class,
UpstreamTag::class
), E_USER_DEPRECATED);
if (! $object instanceof ListObject) {
throw new InvalidArgumentException('Not a valid CoseEncrypt0 object. No list.');
}
if ($object->count() !== 3) {
throw new InvalidArgumentException('Not a valid CoseEncrypt0 object. The list shall have 3 items.');
}
$protectedHeader = $object->get(0);
$unprotectedHeader = $object->get(1);
$ciphertext = $object->get(2);
if (! $protectedHeader instanceof ByteStringObject) {
throw new InvalidArgumentException(
'Not a valid CoseEncrypt0 object. The item 1 shall be a ByteString object.'
);
}
if (! $unprotectedHeader instanceof MapObject) {
throw new InvalidArgumentException('Not a valid CoseEncrypt0 object. The item 2 shall be a Map object.');
}
if (! $ciphertext instanceof ByteStringObject) {
throw new InvalidArgumentException(
'Not a valid CoseEncrypt0 object. The item 3 shall be a ByteString object.'
);
}
parent::__construct($additionalInformation, $data, $object);
$this->protectedHeader = $protectedHeader;
$this->unprotectedHeader = $unprotectedHeader;
$this->ciphertext = $ciphertext;
}
public static function getTagId(): int
{
return self::TAG_ID;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): self
{
return new self($additionalInformation, $data, $object);
}
public static function create(
MapObject $protectedHeader,
MapObject $unprotectedHeader,
ByteStringObject $ciphertext
): self {
$protectedHeaderAsBytesString = ByteStringObject::create((string) $protectedHeader);
$object = ListObject::create([$protectedHeaderAsBytesString, $unprotectedHeader, $ciphertext]);
[$additionalInformation, $data] = self::determineComponents(self::TAG_ID);
return new self($additionalInformation, $data, $object);
}
public function getProtectedHeader(): ByteStringObject
{
return $this->protectedHeader;
}
/**
* The nesting bound only applies to the decoder created here: a caller passing its own $decoder sets its own
* bound, and $maxDepth is then ignored.
*/
public function getProtectedHeaderAsMap(
?Decoder $decoder = null,
int $maxDepth = self::DEFAULT_PROTECTED_HEADER_MAX_DEPTH
): MapObject {
$stream = new StringStream($this->protectedHeader->getValue());
$decoder ??= Decoder::create(TagManager::create(), OtherObjectManager::create(), $maxDepth);
$decoded = $decoder->decode($stream);
if (! $decoded instanceof MapObject) {
throw new InvalidArgumentException('Protected header is not a valid Map object.');
}
return $decoded;
}
public function getUnprotectedHeader(): MapObject
{
return $this->unprotectedHeader;
}
public function getCiphertext(): ByteStringObject
{
return $this->ciphertext;
}
}

View file

@ -0,0 +1,173 @@
<?php
declare(strict_types=1);
namespace Cose\Encryption;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\Decoder;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\OtherObject\OtherObjectManager;
use CBOR\StringStream;
use CBOR\Tag;
use CBOR\Tag\CoseEncryptTag as UpstreamTag;
use CBOR\Tag\TagManager;
use const E_USER_DEPRECATED;
use InvalidArgumentException;
use function sprintf;
use function trigger_error;
/**
* A tagged COSE_Encrypt (RFC 9052, CBOR tag 96).
*
* @deprecated since 4.8.0, use \CBOR\Tag\CoseEncryptTag from spomky-labs/cbor-php 3.4.0 or later instead. Will be removed
* in 5.0.0.
*
* The six COSE structures were ported upstream in cbor-php 3.4.0, where they share AbstractCoseTag and are
* registered in the default decoder, so Decoder::create() resolves tag 96 on its own. The replacement accepts what
* this class rejects -- a zero-length protected header, a detached (nil) payload, the indefinite-length encodings --
* and reads every item through the list it carries, so its accessors cannot drift from the bytes it serializes.
*
* What does not move upstream is the RFC 9052 layer above the CBOR shape, and that stays here: {@see \Cose\Structure\CoseHeaders}
* for header labels typed as RFC 9052 section 1.5 defines them, and the Sig_structure, MAC_structure and
* Enc_structure builders that a signature or a MAC is actually computed over. Both work on the upstream classes.
*
* Migrating: the class name changes, and the four-argument create() becomes createFromComponents() -- upstream
* create() takes the whole list instead.
*
* @see https://github.com/web-auth/cose-lib/issues/176
* @see \Cose\Tests\Structure\DeprecatedTagClassesTest
*/
final class CoseEncryptTag extends Tag
{
/**
* A COSE header is a flat map of a handful of parameters whose values nest a couple of levels at most, so the
* decoder built when none is given is bounded far below the cbor-php default of 1000: a protected header crafted
* to nest thousands of levels is rejected instead of being walked.
*/
public const DEFAULT_PROTECTED_HEADER_MAX_DEPTH = 32;
private const TAG_ID = 96;
private readonly ByteStringObject $protectedHeader;
private readonly MapObject $unprotectedHeader;
private readonly ByteStringObject $ciphertext;
private readonly ListObject $recipients;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
trigger_error(sprintf(
'The class "%s" is deprecated since 4.8.0 and will be removed in 5.0.0. Use "%s" from spomky-labs/cbor-php 3.4.0 or later instead.',
self::class,
UpstreamTag::class
), E_USER_DEPRECATED);
if (! $object instanceof ListObject) {
throw new InvalidArgumentException('Not a valid CoseEncrypt object. No list.');
}
if ($object->count() !== 4) {
throw new InvalidArgumentException('Not a valid CoseEncrypt object. The list shall have 4 items.');
}
$protectedHeader = $object->get(0);
$unprotectedHeader = $object->get(1);
$ciphertext = $object->get(2);
$recipients = $object->get(3);
if (! $protectedHeader instanceof ByteStringObject) {
throw new InvalidArgumentException(
'Not a valid CoseEncrypt object. The item 1 shall be a ByteString object.'
);
}
if (! $unprotectedHeader instanceof MapObject) {
throw new InvalidArgumentException('Not a valid CoseEncrypt object. The item 2 shall be a Map object.');
}
if (! $ciphertext instanceof ByteStringObject) {
throw new InvalidArgumentException(
'Not a valid CoseEncrypt object. The item 3 shall be a ByteString object.'
);
}
if (! $recipients instanceof ListObject) {
throw new InvalidArgumentException('Not a valid CoseEncrypt object. The item 4 shall be a List object.');
}
parent::__construct($additionalInformation, $data, $object);
$this->protectedHeader = $protectedHeader;
$this->unprotectedHeader = $unprotectedHeader;
$this->ciphertext = $ciphertext;
$this->recipients = $recipients;
}
public static function getTagId(): int
{
return self::TAG_ID;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): self
{
return new self($additionalInformation, $data, $object);
}
public static function create(
MapObject $protectedHeader,
MapObject $unprotectedHeader,
ByteStringObject $ciphertext,
ListObject $recipients
): self {
$protectedHeaderAsBytesString = ByteStringObject::create((string) $protectedHeader);
$object = ListObject::create([
$protectedHeaderAsBytesString,
$unprotectedHeader,
$ciphertext,
$recipients,
]);
[$additionalInformation, $data] = self::determineComponents(self::TAG_ID);
return new self($additionalInformation, $data, $object);
}
public function getProtectedHeader(): ByteStringObject
{
return $this->protectedHeader;
}
/**
* The nesting bound only applies to the decoder created here: a caller passing its own $decoder sets its own
* bound, and $maxDepth is then ignored.
*/
public function getProtectedHeaderAsMap(
?Decoder $decoder = null,
int $maxDepth = self::DEFAULT_PROTECTED_HEADER_MAX_DEPTH
): MapObject {
$stream = new StringStream($this->protectedHeader->getValue());
$decoder ??= Decoder::create(TagManager::create(), OtherObjectManager::create(), $maxDepth);
$decoded = $decoder->decode($stream);
if (! $decoded instanceof MapObject) {
throw new InvalidArgumentException('Protected header is not a valid Map object.');
}
return $decoded;
}
public function getUnprotectedHeader(): MapObject
{
return $this->unprotectedHeader;
}
public function getCiphertext(): ByteStringObject
{
return $this->ciphertext;
}
public function getRecipients(): ListObject
{
return $this->recipients;
}
}

View file

@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace Cose\Encryption;
use CBOR\ByteStringObject;
use CBOR\IndefiniteLengthByteStringObject;
use Cose\Structure\CoseStructure;
/**
* The Enc_structure of a COSE_Encrypt0 (RFC 9052 section 5.3).
*
* Enc_structure = [ "Encrypt0", protected : empty_or_serialized_map, external_aad : bstr ]
*
* This is the additional authenticated data of the content encryption. Unlike the signature and MAC structures it
* carries no payload: the content itself is what the AEAD encrypts, and this structure is what it authenticates
* alongside it.
*
*
* The fields a decoded message supplies are typed to accept the indefinite-length byte strings the cbor-php
* accessors can hand back, and are kept exactly as they were given: a cryptographic structure has to embed the
* protected bucket byte for byte, or the signature the sender computed over it no longer verifies.
* @see https://www.rfc-editor.org/rfc/rfc9052#section-5.3
* @see \Cose\Tests\Structure\CoseStructureTest
*/
final class Encrypt0Structure extends CoseStructure
{
private readonly ByteStringObject $externalAad;
public function __construct(
private readonly ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
?ByteStringObject $externalAad = null
) {
$this->externalAad = $externalAad ?? self::emptyExternalAad();
}
public static function create(
ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
?ByteStringObject $externalAad = null
): self {
return new self($protectedHeader, $externalAad);
}
public function getProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->protectedHeader;
}
public function getExternalAad(): ByteStringObject
{
return $this->externalAad;
}
protected function context(): string
{
return 'Encrypt0';
}
protected function items(): array
{
return [$this->protectedHeader, $this->externalAad];
}
}

View file

@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace Cose\Encryption;
use CBOR\ByteStringObject;
use CBOR\IndefiniteLengthByteStringObject;
use Cose\Structure\CoseStructure;
/**
* The Enc_structure of a COSE_Encrypt (RFC 9052 section 5.3).
*
* Enc_structure = [ "Encrypt", protected : empty_or_serialized_map, external_aad : bstr ]
*
* This is the additional authenticated data of the content encryption. Unlike the signature and MAC structures it
* carries no payload: the content itself is what the AEAD encrypts, and this structure is what it authenticates
* alongside it.
*
*
* The fields a decoded message supplies are typed to accept the indefinite-length byte strings the cbor-php
* accessors can hand back, and are kept exactly as they were given: a cryptographic structure has to embed the
* protected bucket byte for byte, or the signature the sender computed over it no longer verifies.
* @see https://www.rfc-editor.org/rfc/rfc9052#section-5.3
* @see \Cose\Tests\Structure\CoseStructureTest
*/
final class EncryptStructure extends CoseStructure
{
private readonly ByteStringObject $externalAad;
public function __construct(
private readonly ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
?ByteStringObject $externalAad = null
) {
$this->externalAad = $externalAad ?? self::emptyExternalAad();
}
public static function create(
ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
?ByteStringObject $externalAad = null
): self {
return new self($protectedHeader, $externalAad);
}
public function getProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->protectedHeader;
}
public function getExternalAad(): ByteStringObject
{
return $this->externalAad;
}
protected function context(): string
{
return 'Encrypt';
}
protected function items(): array
{
return [$this->protectedHeader, $this->externalAad];
}
}

View file

@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
namespace Cose\Encryption;
use CBOR\ByteStringObject;
use CBOR\IndefiniteLengthByteStringObject;
use Cose\Structure\CoseStructure;
/**
* The Enc_structure of a recipient (RFC 9052 section 5.3).
*
* Enc_structure = [ context : "Enc_Recipient" / "Mac_Recipient" / "Rec_Recipient", protected :
* empty_or_serialized_map, external_aad : bstr ]
*
* The three remaining contexts of Enc_structure name where the key being wrapped comes from: the recipient of a
* COSE_Encrypt, the recipient of a COSE_Mac, or a recipient nested inside another recipient. Binding the context is
* what stops a wrapped key from being replayed at a different level of the same structure, so it is a named
* constructor rather than a free string.
*
*
* The fields a decoded message supplies are typed to accept the indefinite-length byte strings the cbor-php
* accessors can hand back, and are kept exactly as they were given: a cryptographic structure has to embed the
* protected bucket byte for byte, or the signature the sender computed over it no longer verifies.
* @see https://www.rfc-editor.org/rfc/rfc9052#section-5.3
* @see \Cose\Tests\Structure\CoseStructureTest
*/
final class RecipientStructure extends CoseStructure
{
/**
* The recipient of a COSE_Encrypt.
*/
public const CONTEXT_ENC_RECIPIENT = 'Enc_Recipient';
/**
* The recipient of a COSE_Mac.
*/
public const CONTEXT_MAC_RECIPIENT = 'Mac_Recipient';
/**
* A recipient nested inside another recipient.
*/
public const CONTEXT_REC_RECIPIENT = 'Rec_Recipient';
private readonly ByteStringObject $externalAad;
private function __construct(
private readonly string $context,
private readonly ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
?ByteStringObject $externalAad = null
) {
$this->externalAad = $externalAad ?? self::emptyExternalAad();
}
public static function forEncryptRecipient(
ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
?ByteStringObject $externalAad = null
): self {
return new self(self::CONTEXT_ENC_RECIPIENT, $protectedHeader, $externalAad);
}
public static function forMacRecipient(
ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
?ByteStringObject $externalAad = null
): self {
return new self(self::CONTEXT_MAC_RECIPIENT, $protectedHeader, $externalAad);
}
public static function forNestedRecipient(
ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
?ByteStringObject $externalAad = null
): self {
return new self(self::CONTEXT_REC_RECIPIENT, $protectedHeader, $externalAad);
}
public function getProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->protectedHeader;
}
public function getExternalAad(): ByteStringObject
{
return $this->externalAad;
}
protected function context(): string
{
return $this->context;
}
protected function items(): array
{
return [$this->protectedHeader, $this->externalAad];
}
}

61
vendor/web-auth/cose-lib/src/Hash.php vendored Normal file
View file

@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace Cose;
/**
* @internal
*/
final class Hash
{
private function __construct(
private readonly string $hash,
private readonly int $length,
private readonly string $t
) {
}
public static function sha1(): self
{
return new self('sha1', 20, "\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14");
}
public static function sha256(): self
{
return new self('sha256', 32, "\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20");
}
public static function sha384(): self
{
return new self('sha384', 48, "\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02\x05\x00\x04\x30");
}
public static function sha512(): self
{
return new self('sha512', 64, "\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03\x05\x00\x04\x40");
}
public function getLength(): int
{
return $this->length;
}
/**
* Compute the HMAC.
*/
public function hash(string $text): string
{
return hash($this->hash, $text, true);
}
public function name(): string
{
return $this->hash;
}
public function t(): string
{
return $this->t;
}
}

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;
}
}

View file

@ -0,0 +1,164 @@
<?php
declare(strict_types=1);
namespace Cose\Mac;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\Decoder;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\OtherObject\OtherObjectManager;
use CBOR\StringStream;
use CBOR\Tag;
use CBOR\Tag\CoseMac0Tag as UpstreamTag;
use CBOR\Tag\TagManager;
use const E_USER_DEPRECATED;
use InvalidArgumentException;
use function sprintf;
use function trigger_error;
/**
* A tagged COSE_Mac0 (RFC 9052, CBOR tag 17).
*
* @deprecated since 4.8.0, use \CBOR\Tag\CoseMac0Tag from spomky-labs/cbor-php 3.4.0 or later instead. Will be removed
* in 5.0.0.
*
* The six COSE structures were ported upstream in cbor-php 3.4.0, where they share AbstractCoseTag and are
* registered in the default decoder, so Decoder::create() resolves tag 17 on its own. The replacement accepts what
* this class rejects -- a zero-length protected header, a detached (nil) payload, the indefinite-length encodings --
* and reads every item through the list it carries, so its accessors cannot drift from the bytes it serializes.
*
* What does not move upstream is the RFC 9052 layer above the CBOR shape, and that stays here: {@see \Cose\Structure\CoseHeaders}
* for header labels typed as RFC 9052 section 1.5 defines them, and the Sig_structure, MAC_structure and
* Enc_structure builders that a signature or a MAC is actually computed over. Both work on the upstream classes.
*
* Migrating: the class name changes, and the four-argument create() becomes createFromComponents() -- upstream
* create() takes the whole list instead.
*
* @see https://github.com/web-auth/cose-lib/issues/176
* @see \Cose\Tests\Structure\DeprecatedTagClassesTest
*/
final class CoseMac0Tag extends Tag
{
/**
* A COSE header is a flat map of a handful of parameters whose values nest a couple of levels at most, so the
* decoder built when none is given is bounded far below the cbor-php default of 1000: a protected header crafted
* to nest thousands of levels is rejected instead of being walked.
*/
public const DEFAULT_PROTECTED_HEADER_MAX_DEPTH = 32;
private const TAG_ID = 17;
private readonly ByteStringObject $protectedHeader;
private readonly MapObject $unprotectedHeader;
private readonly ByteStringObject $payload;
private readonly ByteStringObject $tag;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
trigger_error(sprintf(
'The class "%s" is deprecated since 4.8.0 and will be removed in 5.0.0. Use "%s" from spomky-labs/cbor-php 3.4.0 or later instead.',
self::class,
UpstreamTag::class
), E_USER_DEPRECATED);
if (! $object instanceof ListObject) {
throw new InvalidArgumentException('Not a valid CoseMac0 object. No list.');
}
if ($object->count() !== 4) {
throw new InvalidArgumentException('Not a valid CoseMac0 object. The list shall have 4 items.');
}
$protectedHeader = $object->get(0);
$unprotectedHeader = $object->get(1);
$payload = $object->get(2);
$tag = $object->get(3);
if (! $protectedHeader instanceof ByteStringObject) {
throw new InvalidArgumentException('Not a valid CoseMac0 object. The item 1 shall be a ByteString object.');
}
if (! $unprotectedHeader instanceof MapObject) {
throw new InvalidArgumentException('Not a valid CoseMac0 object. The item 2 shall be a Map object.');
}
if (! $payload instanceof ByteStringObject) {
throw new InvalidArgumentException('Not a valid CoseMac0 object. The item 3 shall be a ByteString object.');
}
if (! $tag instanceof ByteStringObject) {
throw new InvalidArgumentException('Not a valid CoseMac0 object. The item 4 shall be a ByteString object.');
}
parent::__construct($additionalInformation, $data, $object);
$this->protectedHeader = $protectedHeader;
$this->unprotectedHeader = $unprotectedHeader;
$this->payload = $payload;
$this->tag = $tag;
}
public static function getTagId(): int
{
return self::TAG_ID;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): self
{
return new self($additionalInformation, $data, $object);
}
public static function create(
MapObject $protectedHeader,
MapObject $unprotectedHeader,
ByteStringObject $payload,
ByteStringObject $tag
): self {
$protectedHeaderAsBytesString = ByteStringObject::create((string) $protectedHeader);
$object = ListObject::create([$protectedHeaderAsBytesString, $unprotectedHeader, $payload, $tag]);
[$additionalInformation, $data] = self::determineComponents(self::TAG_ID);
return new self($additionalInformation, $data, $object);
}
public function getProtectedHeader(): ByteStringObject
{
return $this->protectedHeader;
}
/**
* The nesting bound only applies to the decoder created here: a caller passing its own $decoder sets its own
* bound, and $maxDepth is then ignored.
*/
public function getProtectedHeaderAsMap(
?Decoder $decoder = null,
int $maxDepth = self::DEFAULT_PROTECTED_HEADER_MAX_DEPTH
): MapObject {
$stream = new StringStream($this->protectedHeader->getValue());
$decoder ??= Decoder::create(TagManager::create(), OtherObjectManager::create(), $maxDepth);
$decoded = $decoder->decode($stream);
if (! $decoded instanceof MapObject) {
throw new InvalidArgumentException('Protected header is not a valid Map object.');
}
return $decoded;
}
public function getUnprotectedHeader(): MapObject
{
return $this->unprotectedHeader;
}
public function getPayload(): ByteStringObject
{
return $this->payload;
}
public function getTag(): ByteStringObject
{
return $this->tag;
}
}

View file

@ -0,0 +1,183 @@
<?php
declare(strict_types=1);
namespace Cose\Mac;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\Decoder;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\OtherObject\OtherObjectManager;
use CBOR\StringStream;
use CBOR\Tag;
use CBOR\Tag\CoseMacTag as UpstreamTag;
use CBOR\Tag\TagManager;
use const E_USER_DEPRECATED;
use InvalidArgumentException;
use function sprintf;
use function trigger_error;
/**
* A tagged COSE_Mac (RFC 9052, CBOR tag 97).
*
* @deprecated since 4.8.0, use \CBOR\Tag\CoseMacTag from spomky-labs/cbor-php 3.4.0 or later instead. Will be removed
* in 5.0.0.
*
* The six COSE structures were ported upstream in cbor-php 3.4.0, where they share AbstractCoseTag and are
* registered in the default decoder, so Decoder::create() resolves tag 97 on its own. The replacement accepts what
* this class rejects -- a zero-length protected header, a detached (nil) payload, the indefinite-length encodings --
* and reads every item through the list it carries, so its accessors cannot drift from the bytes it serializes.
*
* What does not move upstream is the RFC 9052 layer above the CBOR shape, and that stays here: {@see \Cose\Structure\CoseHeaders}
* for header labels typed as RFC 9052 section 1.5 defines them, and the Sig_structure, MAC_structure and
* Enc_structure builders that a signature or a MAC is actually computed over. Both work on the upstream classes.
*
* Migrating: the class name changes, and the four-argument create() becomes createFromComponents() -- upstream
* create() takes the whole list instead.
*
* @see https://github.com/web-auth/cose-lib/issues/176
* @see \Cose\Tests\Structure\DeprecatedTagClassesTest
*/
final class CoseMacTag extends Tag
{
/**
* A COSE header is a flat map of a handful of parameters whose values nest a couple of levels at most, so the
* decoder built when none is given is bounded far below the cbor-php default of 1000: a protected header crafted
* to nest thousands of levels is rejected instead of being walked.
*/
public const DEFAULT_PROTECTED_HEADER_MAX_DEPTH = 32;
private const TAG_ID = 97;
private readonly ByteStringObject $protectedHeader;
private readonly MapObject $unprotectedHeader;
private readonly ByteStringObject $payload;
private readonly ByteStringObject $tag;
private readonly ListObject $recipients;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
trigger_error(sprintf(
'The class "%s" is deprecated since 4.8.0 and will be removed in 5.0.0. Use "%s" from spomky-labs/cbor-php 3.4.0 or later instead.',
self::class,
UpstreamTag::class
), E_USER_DEPRECATED);
if (! $object instanceof ListObject) {
throw new InvalidArgumentException('Not a valid CoseMac object. No list.');
}
if ($object->count() !== 5) {
throw new InvalidArgumentException('Not a valid CoseMac object. The list shall have 5 items.');
}
$protectedHeader = $object->get(0);
$unprotectedHeader = $object->get(1);
$payload = $object->get(2);
$tag = $object->get(3);
$recipients = $object->get(4);
if (! $protectedHeader instanceof ByteStringObject) {
throw new InvalidArgumentException('Not a valid CoseMac object. The item 1 shall be a ByteString object.');
}
if (! $unprotectedHeader instanceof MapObject) {
throw new InvalidArgumentException('Not a valid CoseMac object. The item 2 shall be a Map object.');
}
if (! $payload instanceof ByteStringObject) {
throw new InvalidArgumentException('Not a valid CoseMac object. The item 3 shall be a ByteString object.');
}
if (! $tag instanceof ByteStringObject) {
throw new InvalidArgumentException('Not a valid CoseMac object. The item 4 shall be a ByteString object.');
}
if (! $recipients instanceof ListObject) {
throw new InvalidArgumentException('Not a valid CoseMac object. The item 5 shall be a List object.');
}
parent::__construct($additionalInformation, $data, $object);
$this->protectedHeader = $protectedHeader;
$this->unprotectedHeader = $unprotectedHeader;
$this->payload = $payload;
$this->tag = $tag;
$this->recipients = $recipients;
}
public static function getTagId(): int
{
return self::TAG_ID;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): self
{
return new self($additionalInformation, $data, $object);
}
public static function create(
MapObject $protectedHeader,
MapObject $unprotectedHeader,
ByteStringObject $payload,
ByteStringObject $tag,
ListObject $recipients
): self {
$protectedHeaderAsBytesString = ByteStringObject::create((string) $protectedHeader);
$object = ListObject::create([
$protectedHeaderAsBytesString,
$unprotectedHeader,
$payload,
$tag,
$recipients,
]);
[$additionalInformation, $data] = self::determineComponents(self::TAG_ID);
return new self($additionalInformation, $data, $object);
}
public function getProtectedHeader(): ByteStringObject
{
return $this->protectedHeader;
}
/**
* The nesting bound only applies to the decoder created here: a caller passing its own $decoder sets its own
* bound, and $maxDepth is then ignored.
*/
public function getProtectedHeaderAsMap(
?Decoder $decoder = null,
int $maxDepth = self::DEFAULT_PROTECTED_HEADER_MAX_DEPTH
): MapObject {
$stream = new StringStream($this->protectedHeader->getValue());
$decoder ??= Decoder::create(TagManager::create(), OtherObjectManager::create(), $maxDepth);
$decoded = $decoder->decode($stream);
if (! $decoded instanceof MapObject) {
throw new InvalidArgumentException('Protected header is not a valid Map object.');
}
return $decoded;
}
public function getUnprotectedHeader(): MapObject
{
return $this->unprotectedHeader;
}
public function getPayload(): ByteStringObject
{
return $this->payload;
}
public function getTag(): ByteStringObject
{
return $this->tag;
}
public function getRecipients(): ListObject
{
return $this->recipients;
}
}

View file

@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace Cose\Mac;
use CBOR\ByteStringObject;
use CBOR\IndefiniteLengthByteStringObject;
use Cose\Structure\CoseStructure;
/**
* The MAC_structure of a COSE_Mac0 (RFC 9052 section 6.3).
*
* MAC_structure = [ "MAC0", protected : empty_or_serialized_map, external_aad : bstr, payload : bstr ]
*
* This is what the MAC algorithm authenticates. MACing the payload on its own instead binds the tag neither to the
* protected header -- the algorithm and the key identifier the sender chose -- nor to the message type, so a tag
* computed for a COSE_Mac0 would be accepted for a COSE_Mac and the reverse.
*
*
* The fields a decoded message supplies are typed to accept the indefinite-length byte strings the cbor-php
* accessors can hand back, and are kept exactly as they were given: a cryptographic structure has to embed the
* protected bucket byte for byte, or the signature the sender computed over it no longer verifies.
* @see https://www.rfc-editor.org/rfc/rfc9052#section-6.3
* @see \Cose\Tests\Structure\CoseStructureTest
*/
final class Mac0Structure extends CoseStructure
{
private readonly ByteStringObject $externalAad;
public function __construct(
private readonly ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
private readonly ByteStringObject|IndefiniteLengthByteStringObject $payload,
?ByteStringObject $externalAad = null
) {
$this->externalAad = $externalAad ?? self::emptyExternalAad();
}
public static function create(
ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
ByteStringObject|IndefiniteLengthByteStringObject $payload,
?ByteStringObject $externalAad = null
): self {
return new self($protectedHeader, $payload, $externalAad);
}
public function getProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->protectedHeader;
}
public function getPayload(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->payload;
}
public function getExternalAad(): ByteStringObject
{
return $this->externalAad;
}
protected function context(): string
{
return 'MAC0';
}
protected function items(): array
{
return [$this->protectedHeader, $this->externalAad, $this->payload];
}
}

View file

@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace Cose\Mac;
use CBOR\ByteStringObject;
use CBOR\IndefiniteLengthByteStringObject;
use Cose\Structure\CoseStructure;
/**
* The MAC_structure of a COSE_Mac (RFC 9052 section 6.3).
*
* MAC_structure = [ "MAC", protected : empty_or_serialized_map, external_aad : bstr, payload : bstr ]
*
* This is what the MAC algorithm authenticates, over the body protected header of the message. The context string
* is the only difference with {@see Mac0Structure}, and it is what keeps a tag computed for a multi-recipient
* COSE_Mac from being accepted on a COSE_Mac0 built over the same header and payload.
*
*
* The fields a decoded message supplies are typed to accept the indefinite-length byte strings the cbor-php
* accessors can hand back, and are kept exactly as they were given: a cryptographic structure has to embed the
* protected bucket byte for byte, or the signature the sender computed over it no longer verifies.
* @see https://www.rfc-editor.org/rfc/rfc9052#section-6.3
* @see \Cose\Tests\Structure\CoseStructureTest
*/
final class MacStructure extends CoseStructure
{
private readonly ByteStringObject $externalAad;
public function __construct(
private readonly ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
private readonly ByteStringObject|IndefiniteLengthByteStringObject $payload,
?ByteStringObject $externalAad = null
) {
$this->externalAad = $externalAad ?? self::emptyExternalAad();
}
public static function create(
ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
ByteStringObject|IndefiniteLengthByteStringObject $payload,
?ByteStringObject $externalAad = null
): self {
return new self($protectedHeader, $payload, $externalAad);
}
public function getProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->protectedHeader;
}
public function getPayload(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->payload;
}
public function getExternalAad(): ByteStringObject
{
return $this->externalAad;
}
protected function context(): string
{
return 'MAC';
}
protected function items(): array
{
return [$this->protectedHeader, $this->externalAad, $this->payload];
}
}

View file

@ -0,0 +1,170 @@
<?php
declare(strict_types=1);
namespace Cose\Signature;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\Decoder;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\OtherObject\OtherObjectManager;
use CBOR\StringStream;
use CBOR\Tag;
use CBOR\Tag\CoseSign1Tag as UpstreamTag;
use CBOR\Tag\TagManager;
use const E_USER_DEPRECATED;
use InvalidArgumentException;
use function sprintf;
use function trigger_error;
/**
* A tagged COSE_Sign1 (RFC 9052, CBOR tag 18).
*
* @deprecated since 4.8.0, use \CBOR\Tag\CoseSign1Tag from spomky-labs/cbor-php 3.4.0 or later instead. Will be removed
* in 5.0.0.
*
* The six COSE structures were ported upstream in cbor-php 3.4.0, where they share AbstractCoseTag and are
* registered in the default decoder, so Decoder::create() resolves tag 18 on its own. The replacement accepts what
* this class rejects -- a zero-length protected header, a detached (nil) payload, the indefinite-length encodings --
* and reads every item through the list it carries, so its accessors cannot drift from the bytes it serializes.
*
* What does not move upstream is the RFC 9052 layer above the CBOR shape, and that stays here: {@see \Cose\Structure\CoseHeaders}
* for header labels typed as RFC 9052 section 1.5 defines them, and the Sig_structure, MAC_structure and
* Enc_structure builders that a signature or a MAC is actually computed over. Both work on the upstream classes.
*
* Migrating: the class name changes, and the four-argument create() becomes createFromComponents() -- upstream
* create() takes the whole list instead.
*
* @see https://github.com/web-auth/cose-lib/issues/176
* @see \Cose\Tests\Structure\DeprecatedTagClassesTest
*/
final class CoseSign1Tag extends Tag
{
/**
* A COSE header is a flat map of a handful of parameters whose values nest a couple of levels at most, so the
* decoder built when none is given is bounded far below the cbor-php default of 1000: a protected header crafted
* to nest thousands of levels is rejected instead of being walked.
*/
public const DEFAULT_PROTECTED_HEADER_MAX_DEPTH = 32;
private const TAG_ID = 18;
private readonly ByteStringObject $protectedHeader;
private readonly MapObject $unprotectedHeader;
private readonly ByteStringObject $payload;
private readonly ByteStringObject $signature;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
trigger_error(sprintf(
'The class "%s" is deprecated since 4.8.0 and will be removed in 5.0.0. Use "%s" from spomky-labs/cbor-php 3.4.0 or later instead.',
self::class,
UpstreamTag::class
), E_USER_DEPRECATED);
if (! $object instanceof ListObject) {
throw new InvalidArgumentException('Not a valid CoseSign1 object. No list.');
}
if ($object->count() !== 4) {
throw new InvalidArgumentException('Not a valid CoseSign1 object. The list shall have 4 items.');
}
$protectedHeader = $object->get(0);
$unprotectedHeader = $object->get(1);
$payload = $object->get(2);
$signature = $object->get(3);
if (! $protectedHeader instanceof ByteStringObject) {
throw new InvalidArgumentException(
'Not a valid CoseSign1 object. The item 1 shall be a ByteString object.'
);
}
if (! $unprotectedHeader instanceof MapObject) {
throw new InvalidArgumentException('Not a valid CoseSign1 object. The item 2 shall be a Map object.');
}
if (! $payload instanceof ByteStringObject) {
throw new InvalidArgumentException(
'Not a valid CoseSign1 object. The item 3 shall be a ByteString object.'
);
}
if (! $signature instanceof ByteStringObject) {
throw new InvalidArgumentException(
'Not a valid CoseSign1 object. The item 4 shall be a ByteString object.'
);
}
parent::__construct($additionalInformation, $data, $object);
$this->protectedHeader = $protectedHeader;
$this->unprotectedHeader = $unprotectedHeader;
$this->payload = $payload;
$this->signature = $signature;
}
public static function getTagId(): int
{
return self::TAG_ID;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): self
{
return new self($additionalInformation, $data, $object);
}
public static function create(
MapObject $protectedHeader,
MapObject $unprotectedHeader,
ByteStringObject $payload,
ByteStringObject $signature
): self {
$protectedHeaderAsBytesString = ByteStringObject::create((string) $protectedHeader);
$object = ListObject::create([$protectedHeaderAsBytesString, $unprotectedHeader, $payload, $signature]);
[$additionalInformation, $data] = self::determineComponents(self::TAG_ID);
return new self($additionalInformation, $data, $object);
}
public function getProtectedHeader(): ByteStringObject
{
return $this->protectedHeader;
}
/**
* The nesting bound only applies to the decoder created here: a caller passing its own $decoder sets its own
* bound, and $maxDepth is then ignored.
*/
public function getProtectedHeaderAsMap(
?Decoder $decoder = null,
int $maxDepth = self::DEFAULT_PROTECTED_HEADER_MAX_DEPTH
): MapObject {
$stream = new StringStream($this->protectedHeader->getValue());
$decoder ??= Decoder::create(TagManager::create(), OtherObjectManager::create(), $maxDepth);
$decoded = $decoder->decode($stream);
if (! $decoded instanceof MapObject) {
throw new InvalidArgumentException('Protected header is not a valid Map object.');
}
return $decoded;
}
public function getUnprotectedHeader(): MapObject
{
return $this->unprotectedHeader;
}
public function getPayload(): ByteStringObject
{
return $this->payload;
}
public function getSignature(): ByteStringObject
{
return $this->signature;
}
}

View file

@ -0,0 +1,164 @@
<?php
declare(strict_types=1);
namespace Cose\Signature;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\Decoder;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\OtherObject\OtherObjectManager;
use CBOR\StringStream;
use CBOR\Tag;
use CBOR\Tag\CoseSignTag as UpstreamTag;
use CBOR\Tag\TagManager;
use const E_USER_DEPRECATED;
use InvalidArgumentException;
use function sprintf;
use function trigger_error;
/**
* A tagged COSE_Sign (RFC 9052, CBOR tag 98).
*
* @deprecated since 4.8.0, use \CBOR\Tag\CoseSignTag from spomky-labs/cbor-php 3.4.0 or later instead. Will be removed
* in 5.0.0.
*
* The six COSE structures were ported upstream in cbor-php 3.4.0, where they share AbstractCoseTag and are
* registered in the default decoder, so Decoder::create() resolves tag 98 on its own. The replacement accepts what
* this class rejects -- a zero-length protected header, a detached (nil) payload, the indefinite-length encodings --
* and reads every item through the list it carries, so its accessors cannot drift from the bytes it serializes.
*
* What does not move upstream is the RFC 9052 layer above the CBOR shape, and that stays here: {@see \Cose\Structure\CoseHeaders}
* for header labels typed as RFC 9052 section 1.5 defines them, and the Sig_structure, MAC_structure and
* Enc_structure builders that a signature or a MAC is actually computed over. Both work on the upstream classes.
*
* Migrating: the class name changes, and the four-argument create() becomes createFromComponents() -- upstream
* create() takes the whole list instead.
*
* @see https://github.com/web-auth/cose-lib/issues/176
* @see \Cose\Tests\Structure\DeprecatedTagClassesTest
*/
final class CoseSignTag extends Tag
{
/**
* A COSE header is a flat map of a handful of parameters whose values nest a couple of levels at most, so the
* decoder built when none is given is bounded far below the cbor-php default of 1000: a protected header crafted
* to nest thousands of levels is rejected instead of being walked.
*/
public const DEFAULT_PROTECTED_HEADER_MAX_DEPTH = 32;
private const TAG_ID = 98;
private readonly ByteStringObject $protectedHeader;
private readonly MapObject $unprotectedHeader;
private readonly ByteStringObject $payload;
private readonly ListObject $signatures;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
trigger_error(sprintf(
'The class "%s" is deprecated since 4.8.0 and will be removed in 5.0.0. Use "%s" from spomky-labs/cbor-php 3.4.0 or later instead.',
self::class,
UpstreamTag::class
), E_USER_DEPRECATED);
if (! $object instanceof ListObject) {
throw new InvalidArgumentException('Not a valid CoseSign object. No list.');
}
if ($object->count() !== 4) {
throw new InvalidArgumentException('Not a valid CoseSign object. The list shall have 4 items.');
}
$protectedHeader = $object->get(0);
$unprotectedHeader = $object->get(1);
$payload = $object->get(2);
$signatures = $object->get(3);
if (! $protectedHeader instanceof ByteStringObject) {
throw new InvalidArgumentException('Not a valid CoseSign object. The item 1 shall be a ByteString object.');
}
if (! $unprotectedHeader instanceof MapObject) {
throw new InvalidArgumentException('Not a valid CoseSign object. The item 2 shall be a Map object.');
}
if (! $payload instanceof ByteStringObject) {
throw new InvalidArgumentException('Not a valid CoseSign object. The item 3 shall be a ByteString object.');
}
if (! $signatures instanceof ListObject) {
throw new InvalidArgumentException('Not a valid CoseSign object. The item 4 shall be a List object.');
}
parent::__construct($additionalInformation, $data, $object);
$this->protectedHeader = $protectedHeader;
$this->unprotectedHeader = $unprotectedHeader;
$this->payload = $payload;
$this->signatures = $signatures;
}
public static function getTagId(): int
{
return self::TAG_ID;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): self
{
return new self($additionalInformation, $data, $object);
}
public static function create(
MapObject $protectedHeader,
MapObject $unprotectedHeader,
ByteStringObject $payload,
ListObject $signatures
): self {
$protectedHeaderAsBytesString = ByteStringObject::create((string) $protectedHeader);
$object = ListObject::create([$protectedHeaderAsBytesString, $unprotectedHeader, $payload, $signatures]);
[$additionalInformation, $data] = self::determineComponents(self::TAG_ID);
return new self($additionalInformation, $data, $object);
}
public function getProtectedHeader(): ByteStringObject
{
return $this->protectedHeader;
}
/**
* The nesting bound only applies to the decoder created here: a caller passing its own $decoder sets its own
* bound, and $maxDepth is then ignored.
*/
public function getProtectedHeaderAsMap(
?Decoder $decoder = null,
int $maxDepth = self::DEFAULT_PROTECTED_HEADER_MAX_DEPTH
): MapObject {
$stream = new StringStream($this->protectedHeader->getValue());
$decoder ??= Decoder::create(TagManager::create(), OtherObjectManager::create(), $maxDepth);
$decoded = $decoder->decode($stream);
if (! $decoded instanceof MapObject) {
throw new InvalidArgumentException('Protected header is not a valid Map object.');
}
return $decoded;
}
public function getUnprotectedHeader(): MapObject
{
return $this->unprotectedHeader;
}
public function getPayload(): ByteStringObject
{
return $this->payload;
}
public function getSignatures(): ListObject
{
return $this->signatures;
}
}

View file

@ -0,0 +1,136 @@
<?php
declare(strict_types=1);
namespace Cose\Signature;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\IndefiniteLengthMapObject;
use CBOR\ListObject;
use CBOR\MapObject;
use Cose\Structure\CoseHeaders;
use Cose\Structure\HeaderMapHelper;
use InvalidArgumentException;
/**
* One entry of the "signatures" list of a COSE_Sign (RFC 9052 section 4.1).
*
* COSE_Signature = [ Headers, signature : bstr ]
*
* The raw list a message carries says nothing about what is inside it, and neither cbor-php nor the deprecated
* Cose\Signature\CoseSignTag looks: both accept an empty list and entries of any shape. This view is the checked
* form, and it carries the same header reader as the message, because a signer of a COSE_Sign has a protected
* bucket of its own that its signature commits to.
*
* ```php
* foreach ($message->getSignatures() as $entry) {
* $signer = CoseSignature::create($entry);
* $toBeSigned = Signature::create(
* $message->getProtectedHeader(),
* $signer->getProtectedHeader(),
* $message->getPayload(),
* );
* }
* ```
*
* @see https://www.rfc-editor.org/rfc/rfc9052#section-4.1
* @see \Cose\Tests\Structure\CoseSignatureTest
*/
final class CoseSignature
{
private readonly ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader;
private readonly MapObject|IndefiniteLengthMapObject $unprotectedHeader;
private readonly ByteStringObject|IndefiniteLengthByteStringObject $signature;
public function __construct(ListObject|IndefiniteLengthListObject $signature)
{
HeaderMapHelper::assertSignatureList(ListObject::create([$signature]));
/** @var ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader */
$protectedHeader = $signature->get(0);
/** @var IndefiniteLengthMapObject|MapObject $unprotectedHeader */
$unprotectedHeader = $signature->get(1);
/** @var ByteStringObject|IndefiniteLengthByteStringObject $signatureValue */
$signatureValue = $signature->get(2);
$this->protectedHeader = $protectedHeader;
$this->unprotectedHeader = $unprotectedHeader;
$this->signature = $signatureValue;
}
public static function create(ListObject|IndefiniteLengthListObject $signature): self
{
return new self($signature);
}
/**
* Every entry of a "signatures" list, checked and wrapped.
*
* @return list<self>
*/
public static function all(ListObject|IndefiniteLengthListObject $signatures): array
{
HeaderMapHelper::assertSignatureList($signatures);
$result = [];
foreach ($signatures as $signature) {
if (! $signature instanceof ListObject && ! $signature instanceof IndefiniteLengthListObject) {
throw new InvalidArgumentException('Not a valid COSE_Signature object. It shall be a List object.');
}
$result[] = new self($signature);
}
return $result;
}
/**
* The protected bucket of this signer, as it is carried: what its Sig_structure covers verbatim.
*/
public function getProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->protectedHeader;
}
public function getUnprotectedHeader(): MapObject|IndefiniteLengthMapObject
{
return $this->unprotectedHeader;
}
/**
* The headers of this signer, read the way RFC 9052 defines them.
*/
public function headers(): CoseHeaders
{
return CoseHeaders::of($this->protectedHeader, $this->unprotectedHeader);
}
public function getProtectedHeaderParameter(int|string $label): ?CBORObject
{
return $this->headers()
->getProtectedHeaderParameter($label);
}
public function getUnprotectedHeaderParameter(int|string $label): ?CBORObject
{
return $this->headers()
->getUnprotectedHeaderParameter($label);
}
public function getSignature(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->signature;
}
/**
* The list this view was built from, rebuilt so that nothing the caller does to it reaches the message.
*/
public function toListObject(): ListObject
{
return ListObject::create([$this->protectedHeader, $this->unprotectedHeader, $this->signature]);
}
}

View file

@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace Cose\Signature;
use CBOR\ByteStringObject;
use CBOR\IndefiniteLengthByteStringObject;
use Cose\Structure\CoseStructure;
/**
* The Sig_structure of one signer of a COSE_Sign (RFC 9052 section 4.4).
*
* Sig_structure = [ "Signature", body_protected : empty_or_serialized_map, sign_protected : empty_or_serialized_map,
* external_aad : bstr, payload : bstr ]
*
* The sign_protected field is what tells this structure apart from {@see Signature1}: a signature of a COSE_Sign
* commits to the protected bucket of the message *and* to the one of its own COSE_Signature entry. Without it, a
* per-signer signature would be byte-identical to a COSE_Sign1 signature over the same header and payload.
*
*
* The fields a decoded message supplies are typed to accept the indefinite-length byte strings the cbor-php
* accessors can hand back, and are kept exactly as they were given: a cryptographic structure has to embed the
* protected bucket byte for byte, or the signature the sender computed over it no longer verifies.
* @see https://www.rfc-editor.org/rfc/rfc9052#section-4.4
* @see \Cose\Tests\Structure\CoseStructureTest
*/
final class Signature extends CoseStructure
{
private readonly ByteStringObject $externalAad;
public function __construct(
private readonly ByteStringObject|IndefiniteLengthByteStringObject $bodyProtectedHeader,
private readonly ByteStringObject|IndefiniteLengthByteStringObject $signProtectedHeader,
private readonly ByteStringObject|IndefiniteLengthByteStringObject $payload,
?ByteStringObject $externalAad = null
) {
$this->externalAad = $externalAad ?? self::emptyExternalAad();
}
public static function create(
ByteStringObject|IndefiniteLengthByteStringObject $bodyProtectedHeader,
ByteStringObject|IndefiniteLengthByteStringObject $signProtectedHeader,
ByteStringObject|IndefiniteLengthByteStringObject $payload,
?ByteStringObject $externalAad = null
): self {
return new self($bodyProtectedHeader, $signProtectedHeader, $payload, $externalAad);
}
public function getBodyProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->bodyProtectedHeader;
}
public function getSignProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->signProtectedHeader;
}
public function getPayload(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->payload;
}
public function getExternalAad(): ByteStringObject
{
return $this->externalAad;
}
protected function context(): string
{
return 'Signature';
}
protected function items(): array
{
return [$this->bodyProtectedHeader, $this->signProtectedHeader, $this->externalAad, $this->payload];
}
}

View file

@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace Cose\Signature;
use CBOR\ByteStringObject;
use CBOR\IndefiniteLengthByteStringObject;
use Cose\Structure\CoseStructure;
/**
* The Sig_structure of a COSE_Sign1 (RFC 9052 section 4.4).
*
* Sig_structure = [ "Signature1", body_protected : empty_or_serialized_map, external_aad : bstr, payload : bstr ]
*
* The payload is a parameter rather than something read back from the message so that a detached payload -- the nil
* form of RFC 9052 section 4.2 -- is supplied by the application, which is what the RFC requires of it.
*
*
* The fields a decoded message supplies are typed to accept the indefinite-length byte strings the cbor-php
* accessors can hand back, and are kept exactly as they were given: a cryptographic structure has to embed the
* protected bucket byte for byte, or the signature the sender computed over it no longer verifies.
* @see https://www.rfc-editor.org/rfc/rfc9052#section-4.4
* @see \Cose\Tests\Signature\CoseSign1CreateAndVerifyTest
*/
final class Signature1 extends CoseStructure
{
private readonly ByteStringObject $externalAad;
public function __construct(
private readonly ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
private readonly ByteStringObject|IndefiniteLengthByteStringObject $payload,
?ByteStringObject $externalAad = null
) {
$this->externalAad = $externalAad ?? self::emptyExternalAad();
}
public static function create(
ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
ByteStringObject|IndefiniteLengthByteStringObject $payload,
?ByteStringObject $externalAad = null
): self {
return new self($protectedHeader, $payload, $externalAad);
}
public function getProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->protectedHeader;
}
public function getPayload(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->payload;
}
public function getExternalAad(): ByteStringObject
{
return $this->externalAad;
}
protected function context(): string
{
return 'Signature1';
}
protected function items(): array
{
return [$this->protectedHeader, $this->externalAad, $this->payload];
}
}

View file

@ -0,0 +1,151 @@
<?php
declare(strict_types=1);
namespace Cose\Structure;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\DecoderInterface;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\IndefiniteLengthMapObject;
use CBOR\MapObject;
use CBOR\Tag\AbstractCoseTag;
/**
* The two header buckets of a COSE message, read the way RFC 9052 defines them.
*
* cbor-php 3.4.0 owns the shape of a COSE message and hands back the buckets as they were encoded. What it does not
* do -- and what a CBOR library has no business doing -- is apply the header rules of RFC 9052 sections 1.5 and 3 on
* top: a label is an integer or a text string and nothing else, the two are distinct even when they normalize to the
* same map offset, a label appears at most once, and the protected bucket holds exactly one CBOR item.
*
* That is what this reads. It works on any COSE message: the upstream classes through fromMessage(), the deprecated
* Cose\...Tag classes and the per-signer or per-recipient entries through of().
*
* ```php
* $message = Decoder::create()->decode(StringStream::create($bytes)); // CBOR\Tag\CoseSign1Tag
* $headers = CoseHeaders::fromMessage($message);
*
* $alg = $headers->getProtectedHeaderParameter(1); // never answered by the text string "1"
* $kid = $headers->getHeaderParameter(4); // protected bucket first
* ```
*
* The protected bucket is decoded once, on first use.
*
* @see https://www.rfc-editor.org/rfc/rfc9052#section-3
* @see https://github.com/web-auth/cose-lib/issues/166
* @see \Cose\Tests\Structure\CoseHeadersTest
*/
final class CoseHeaders
{
public const DEFAULT_PROTECTED_HEADER_MAX_DEPTH = HeaderMapHelper::DEFAULT_PROTECTED_HEADER_MAX_DEPTH;
private ?MapObject $decodedProtectedHeader = null;
private function __construct(
private readonly ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
private readonly MapObject|IndefiniteLengthMapObject $unprotectedHeader,
private readonly ?DecoderInterface $decoder,
private readonly int $maxDepth
) {
}
/**
* The buckets of a COSE message, given as they are carried.
*
* This is the form to use for a per-signer COSE_Signature or a COSE_recipient -- {@see CoseSignature} and
* {@see CoseRecipient} build it for you -- and for the deprecated Cose\...Tag classes.
*/
public static function of(
ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
MapObject|IndefiniteLengthMapObject $unprotectedHeader,
?DecoderInterface $decoder = null,
int $maxDepth = self::DEFAULT_PROTECTED_HEADER_MAX_DEPTH
): self {
return new self($protectedHeader, $unprotectedHeader, $decoder, $maxDepth);
}
/**
* The buckets of one of the six COSE messages of cbor-php 3.4.0 or later.
*
* The nesting bound only applies to the decoder built when none is given: a caller passing its own $decoder sets
* its own bound, and $maxDepth is then ignored.
*/
public static function fromMessage(
AbstractCoseTag $message,
?DecoderInterface $decoder = null,
int $maxDepth = self::DEFAULT_PROTECTED_HEADER_MAX_DEPTH
): self {
return new self($message->getProtectedHeader(), $message->getUnprotectedHeader(), $decoder, $maxDepth);
}
/**
* The protected bucket as it is carried: the byte string the cryptographic structure covers verbatim.
*/
public function getProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->protectedHeader;
}
/**
* The protected bucket, decoded and checked: the zero-length byte string of RFC 9052 section 3 is an empty
* header, trailing bytes after the header map are rejected, and every key is a label.
*/
public function getProtectedHeaderAsMap(): MapObject
{
return $this->decodedProtectedHeader ??= HeaderMapHelper::decodeProtected(
$this->protectedHeader,
$this->decoder,
$this->maxDepth
);
}
/**
* The unprotected bucket, with its labels checked.
*/
public function getUnprotectedHeaderAsMap(): MapObject
{
return HeaderMapHelper::assertValidLabels($this->unprotectedHeader);
}
/**
* The unprotected bucket as it is carried.
*/
public function getUnprotectedHeader(): MapObject|IndefiniteLengthMapObject
{
return $this->unprotectedHeader;
}
/**
* The value of a label in the protected bucket, or null when the bucket does not carry it.
*
* The label is matched by type as well as by value, so the integer 1 -- the algorithm -- is never answered by
* the text string "1" or by a byte string that happens to normalize the same way.
*/
public function getProtectedHeaderParameter(int|string $label): ?CBORObject
{
return HeaderMapHelper::findLabel($this->getProtectedHeaderAsMap(), $label);
}
/**
* The value of a label in the unprotected bucket, or null when the bucket does not carry it.
*/
public function getUnprotectedHeaderParameter(int|string $label): ?CBORObject
{
return HeaderMapHelper::findLabel($this->unprotectedHeader, $label);
}
/**
* The value of a label, looked up in the protected bucket first.
*
* A parameter found there is the one the signature or the MAC commits to, so it wins over an unprotected copy of
* the same label. A message carrying a label in both buckets is malformed anyway (RFC 9052 section 3: "The same
* label MUST NOT occur in both buckets"); preferring the protected value keeps the answer on the authenticated
* side of that mistake.
*/
public function getHeaderParameter(int|string $label): ?CBORObject
{
return $this->getProtectedHeaderParameter($label) ?? $this->getUnprotectedHeaderParameter($label);
}
}

View file

@ -0,0 +1,167 @@
<?php
declare(strict_types=1);
namespace Cose\Structure;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\IndefiniteLengthMapObject;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\OtherObject\NullObject;
use InvalidArgumentException;
use LogicException;
/**
* One entry of the "recipients" list of a COSE_Encrypt or of a COSE_Mac (RFC 9052 sections 5.1 and 6.1).
*
* COSE_recipient = [ Headers, ciphertext : bstr / nil, ? recipients : [+COSE_recipient] ]
*
* The raw list a message carries says nothing about what is inside it, and neither cbor-php nor the deprecated
* Cose\...Tag classes look: both accept an empty list and entries of any shape. This view is the checked form.
*
* A recipient may itself carry recipients, which is how RFC 9052 expresses key layering; getRecipients() walks that
* tree one level at a time and each level is a view of the same kind.
*
* @see https://www.rfc-editor.org/rfc/rfc9052#section-5.1
* @see \Cose\Tests\Structure\CoseRecipientTest
*/
final class CoseRecipient
{
private readonly ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader;
private readonly MapObject|IndefiniteLengthMapObject $unprotectedHeader;
private readonly ByteStringObject|IndefiniteLengthByteStringObject|null $ciphertext;
private readonly ListObject|IndefiniteLengthListObject|null $recipients;
public function __construct(ListObject|IndefiniteLengthListObject $recipient)
{
HeaderMapHelper::assertRecipientList(ListObject::create([$recipient]));
/** @var ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader */
$protectedHeader = $recipient->get(0);
/** @var IndefiniteLengthMapObject|MapObject $unprotectedHeader */
$unprotectedHeader = $recipient->get(1);
// assertRecipientList() has just ruled out everything but a byte string and nil at this position.
/** @var ByteStringObject|IndefiniteLengthByteStringObject|null $ciphertext */
$ciphertext = HeaderMapHelper::isNil($recipient->get(2)) ? null : $recipient->get(2);
$this->protectedHeader = $protectedHeader;
$this->unprotectedHeader = $unprotectedHeader;
$this->ciphertext = $ciphertext;
$nested = $recipient->count() === 4 ? $recipient->get(3) : null;
$this->recipients = $nested instanceof ListObject || $nested instanceof IndefiniteLengthListObject
? $nested
: null;
}
public static function create(ListObject|IndefiniteLengthListObject $recipient): self
{
return new self($recipient);
}
/**
* Every entry of a "recipients" list, checked and wrapped.
*
* @return list<self>
*/
public static function all(ListObject|IndefiniteLengthListObject $recipients): array
{
HeaderMapHelper::assertRecipientList($recipients);
$result = [];
foreach ($recipients as $recipient) {
if (! $recipient instanceof ListObject && ! $recipient instanceof IndefiniteLengthListObject) {
throw new InvalidArgumentException('Not a valid COSE_recipient object. It shall be a List object.');
}
$result[] = new self($recipient);
}
return $result;
}
/**
* The protected bucket of this recipient, as it is carried.
*/
public function getProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->protectedHeader;
}
public function getUnprotectedHeader(): MapObject|IndefiniteLengthMapObject
{
return $this->unprotectedHeader;
}
/**
* The headers of this recipient, read the way RFC 9052 defines them.
*/
public function headers(): CoseHeaders
{
return CoseHeaders::of($this->protectedHeader, $this->unprotectedHeader);
}
public function getProtectedHeaderParameter(int|string $label): ?CBORObject
{
return $this->headers()
->getProtectedHeaderParameter($label);
}
public function getUnprotectedHeaderParameter(int|string $label): ?CBORObject
{
return $this->headers()
->getUnprotectedHeaderParameter($label);
}
/**
* Whether the ciphertext of this recipient travels outside the message.
*/
public function hasDetachedCiphertext(): bool
{
return $this->ciphertext === null;
}
/**
* @throws LogicException when the ciphertext is detached; hasDetachedCiphertext() tells the two cases apart
*/
public function getCiphertext(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->ciphertext ?? throw new LogicException(
'The ciphertext of this COSE_recipient is detached (RFC 9052 section 5.1); the application supplies it separately.'
);
}
public function hasRecipients(): bool
{
return $this->recipients !== null;
}
/**
* The recipients nested under this one, empty when it carries none.
*
* @return list<self>
*/
public function getRecipients(): array
{
return $this->recipients === null ? [] : self::all($this->recipients);
}
/**
* The list this view was built from, rebuilt so that nothing the caller does to it reaches the message.
*/
public function toListObject(): ListObject
{
$items = [$this->protectedHeader, $this->unprotectedHeader, $this->ciphertext ?? NullObject::create()];
if ($this->recipients !== null) {
$items[] = $this->recipients;
}
return ListObject::create($items);
}
}

View file

@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Cose\Structure;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\ListObject;
use CBOR\TextStringObject;
use Stringable;
/**
* The shape every RFC 9052 cryptographic structure has: a context string that names what is being computed,
* followed by the fields that structure commits to.
*
* These are the byte strings that are signed, MACed or fed as additional authenticated data -- never the payload on
* its own. Casting an instance to string yields the CBOR encoding to hand to the algorithm.
*
* @see https://www.rfc-editor.org/rfc/rfc9052#section-4.4
* @see https://www.rfc-editor.org/rfc/rfc9052#section-5.3
* @see https://www.rfc-editor.org/rfc/rfc9052#section-6.3
*/
abstract class CoseStructure implements Stringable
{
/**
* RFC 9052 section 4.4 on external_aad: "If this field is not supplied, it defaults to a zero-length byte
* string."
*/
public static function emptyExternalAad(): ByteStringObject
{
return ByteStringObject::create('');
}
public function __toString(): string
{
return (string) ListObject::create([TextStringObject::create($this->context()), ...$this->items()]);
}
/**
* The context string of this structure, as RFC 9052 spells it.
*/
abstract protected function context(): string;
/**
* The fields following the context, in the order the CDDL gives them.
*
* @return list<CBORObject>
*/
abstract protected function items(): array;
}

View file

@ -0,0 +1,341 @@
<?php
declare(strict_types=1);
namespace Cose\Structure;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\Decoder;
use CBOR\DecoderInterface;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\IndefiniteLengthMapObject;
use CBOR\IndefiniteLengthTextStringObject;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\NegativeIntegerObject;
use CBOR\OtherObject\OtherObjectInterface;
use CBOR\StringStream;
use CBOR\TextStringObject;
use CBOR\UnsignedIntegerObject;
use function in_array;
use InvalidArgumentException;
use function is_int;
use function ord;
use function sprintf;
use function strlen;
/**
* The RFC 9052 rules that sit above the CBOR shape of a COSE message: how a protected bucket is encoded and decoded,
* what a header label may be, which CBOR tag number a message type carries, and the shape of the signature and
* recipient lists.
*
* These are deliberately static functions over plain CBOR objects rather than methods on a message class. Since
* spomky-labs/cbor-php 3.4.0 the six COSE structures live upstream, as CBOR\Tag\CoseSign1Tag and its siblings: that
* library owns the shape of a message, this one owns what RFC 9052 says the shape means. Everything here therefore
* applies to an upstream message, to the deprecated Cose\...Tag classes, and to a header map a caller assembled
* itself.
*
* {@see CoseHeaders} is the ergonomic form of the header half of this: it reads the two buckets of a message once
* and answers label lookups against them.
*
* @see https://www.rfc-editor.org/rfc/rfc9052#section-3
* @see https://www.rfc-editor.org/rfc/rfc9052#section-1.5
* @see https://github.com/web-auth/cose-lib/issues/166
* @see \Cose\Tests\Structure\HeaderMapHelperTest
*/
final class HeaderMapHelper
{
/**
* A COSE header is a flat map of a handful of parameters whose values nest a couple of levels at most, so the
* decoder built when none is given is bounded far below the cbor-php default of 1000: a protected header crafted
* to nest thousands of levels is rejected instead of being walked.
*/
public const DEFAULT_PROTECTED_HEADER_MAX_DEPTH = 32;
/**
* Decode the protected bucket, strictly.
*
* Three RFC 9052 rules the upstream accessor does not apply, in one place:
*
* - Section 3: "Recipients MUST accept both a zero-length byte string and a zero-length map encoded in a byte
* string." The zero-length byte string is the form senders are told to prefer, and decoding it as CBOR yields
* nothing at all, hence the guard before the decoder runs.
* - Section 3 CDDL: "empty_or_serialized_map = bstr .cbor header_map / bstr .size 0". The ".cbor" control of
* RFC 8610 section 3.8.4 carries exactly one data item, so trailing bytes make the bucket malformed.
* - Section 1.5: a key that is neither an integer nor a text string is not a label at all.
*/
public static function decodeProtected(
ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
?DecoderInterface $decoder = null,
int $maxDepth = self::DEFAULT_PROTECTED_HEADER_MAX_DEPTH
): MapObject {
$raw = $protectedHeader->getValue();
if ($raw === '') {
return MapObject::create();
}
$stream = new StringStream($raw);
$decoder ??= Decoder::create(null, null, $maxDepth);
$decoded = $decoder->decode($stream);
// cbor-php exposes no end-of-stream predicate, so the probe is a read that has to fail.
$trailing = true;
try {
$stream->read(1);
} catch (InvalidArgumentException) {
$trailing = false;
}
if ($trailing) {
throw new InvalidArgumentException(
'Invalid protected header. The byte string carries trailing data after the header map.'
);
}
if (! $decoded instanceof MapObject && ! $decoded instanceof IndefiniteLengthMapObject) {
throw new InvalidArgumentException('Protected header is not a valid Map object.');
}
return self::assertValidLabels($decoded);
}
/**
* Encode the protected bucket.
*
* RFC 9052 section 3: "Senders SHOULD encode a zero-length map as a zero-length byte string rather than as a
* zero-length map (encoded as h'a0')." Upstream createFromComponents() emits h'a0'; a sender that wants the
* preferred form passes the byte string this returns.
*/
public static function encodeProtected(MapObject|IndefiniteLengthMapObject $protectedHeader): ByteStringObject
{
$checked = self::assertValidLabels($protectedHeader);
return ByteStringObject::create($checked->count() === 0 ? '' : (string) $checked);
}
/**
* Check that every key of a header map is a label and that no label appears twice, and hand back an equivalent
* definite-length map.
*
* RFC 9052 section 1.5: "label = int / tstr" and "the presence a label that is neither a text string nor an
* integer is an error". Section 3: "Labels in each of the maps MUST be unique. When processing messages, if a
* label appears multiple times, the message MUST be rejected as malformed." A byte string key is the case worth
* naming: cbor-php normalizes h'31' to the string "1", so without this check a byte string key would answer a
* lookup for the integer label 1, the algorithm parameter.
*/
public static function assertValidLabels(MapObject|IndefiniteLengthMapObject $header): MapObject
{
$checked = MapObject::create();
foreach ($header as $item) {
$key = $item->getKey();
if (! self::isLabel($key)) {
throw new InvalidArgumentException(sprintf(
'Invalid header label. A label shall be an integer or a text string, got "%s" (RFC 9052 section 1.5).',
$key::class
));
}
$checked->add($key, $item->getValue());
}
return $checked;
}
/**
* Look a label up by value *and* by type.
*
* The map accessors of cbor-php are keyed by the normalized key, and PHP turns the numeric string offset "1"
* into the integer 1, so int 1 and tstr "1" -- two distinct labels for RFC 9052 -- share one offset there. This
* lookup compares the major type as well, which is what makes a lookup for the label 1 mean the algorithm
* parameter and nothing else.
*/
public static function findLabel(MapObject|IndefiniteLengthMapObject $header, int|string $label): ?CBORObject
{
foreach ($header as $item) {
$key = $item->getKey();
$matches = is_int($label)
? ($key instanceof UnsignedIntegerObject || $key instanceof NegativeIntegerObject)
&& $key->normalize() === (string) $label
: ($key instanceof TextStringObject || $key instanceof IndefiniteLengthTextStringObject)
&& $key->normalize() === $label;
if ($matches) {
return $item->getValue();
}
}
return null;
}
/**
* Check that the CBOR tag a message carries is the one its structure claims.
*
* RFC 9052 section 2 maps each message type to one tag number, and the decoder dispatches on that number, so
* this is for the paths that bypass it: a class constructed directly, or createFromLoadedData() called on the
* value of a GenericTag. Neither the upstream classes nor the deprecated ones check it, so a message can
* otherwise keep claiming to be a COSE_Sign1 while serializing as a COSE_Mac0.
*
* The comparison is on the decoded number, not on the raw components, so a non-minimal encoding of the right
* number stays acceptable exactly as it is on the decoder path (RFC 8949 allows it outside deterministic
* encoding).
*/
public static function assertTagNumber(int $additionalInformation, ?string $data, int $expected, string $name): void
{
$number = self::tagNumber($additionalInformation, $data, $name);
if ($number !== $expected) {
throw new InvalidArgumentException(sprintf(
'Not a valid %s object. Expected the CBOR tag %d, got %d.',
$name,
$expected,
$number
));
}
}
/**
* Check a "signatures" list against "signatures : [+ COSE_Signature]" and "COSE_Signature = [ Headers,
* signature : bstr ]" (RFC 9052 section 4.1), Headers being the protected byte string and the unprotected map.
*/
public static function assertSignatureList(ListObject|IndefiniteLengthListObject $signatures): void
{
if ($signatures->count() === 0) {
throw new InvalidArgumentException(
'Not a valid CoseSign object. The signatures list shall hold at least one COSE_Signature (RFC 9052 section 4.1).'
);
}
foreach ($signatures as $signature) {
if (! self::isList($signature)
|| $signature->count() !== 3
|| ! self::isByteString($signature->get(0))
|| ! self::isMap($signature->get(1))
|| ! self::isByteString($signature->get(2))
) {
throw new InvalidArgumentException(
'Not a valid CoseSign object. Each signature shall be a COSE_Signature [bstr, map, bstr].'
);
}
}
}
/**
* Check a "recipients" list against "recipients : [+COSE_recipient]" and "COSE_recipient = [ Headers,
* ciphertext : bstr / nil, ? recipients : [+COSE_recipient] ]" (RFC 9052 section 5.1).
*
* The nested list is walked with the same rule, which is what bounds a recipient tree to well-formed levels
* rather than to whatever the decoder happened to accept.
*/
public static function assertRecipientList(
ListObject|IndefiniteLengthListObject $recipients,
string $name = 'COSE_recipient'
): void {
if ($recipients->count() === 0) {
throw new InvalidArgumentException(sprintf(
'Not a valid %s object. The recipients list shall hold at least one COSE_recipient (RFC 9052 section 5.1).',
$name
));
}
foreach ($recipients as $recipient) {
if (! self::isList($recipient)
|| ! in_array($recipient->count(), [3, 4], true)
|| ! self::isByteString($recipient->get(0))
|| ! self::isMap($recipient->get(1))
|| ! (self::isByteString($recipient->get(2)) || self::isNil($recipient->get(2)))
) {
throw new InvalidArgumentException(sprintf(
'Not a valid %s object. Each recipient shall be a COSE_recipient [bstr, map, bstr / nil, ? [+ COSE_recipient]].',
$name
));
}
if ($recipient->count() === 4) {
$nested = $recipient->get(3);
if (! self::isList($nested)) {
throw new InvalidArgumentException(sprintf(
'Not a valid %s object. The nested recipients of a COSE_recipient shall be a List object.',
$name
));
}
self::assertRecipientList($nested, $name);
}
}
}
/**
* Whether an item is the CBOR "nil" simple value, which is how RFC 9052 spells detached content.
*
* The decoder maps simple value 22 to NullObject only when the caller's OtherObjectManager knows that class; an
* empty manager yields a GenericObject carrying the same head. Both are nil on the wire, so both are nil here.
*/
public static function isNil(CBORObject $object): bool
{
return $object instanceof OtherObjectInterface
&& $object->getAdditionalInformation() === CBORObject::OBJECT_NULL;
}
/**
* @phpstan-assert-if-true IndefiniteLengthListObject|ListObject $object
*/
private static function isList(CBORObject $object): bool
{
return $object instanceof ListObject || $object instanceof IndefiniteLengthListObject;
}
private static function isMap(CBORObject $object): bool
{
return $object instanceof MapObject || $object instanceof IndefiniteLengthMapObject;
}
private static function isByteString(CBORObject $object): bool
{
return $object instanceof ByteStringObject || $object instanceof IndefiniteLengthByteStringObject;
}
private static function isLabel(CBORObject $key): bool
{
return $key instanceof UnsignedIntegerObject
|| $key instanceof NegativeIntegerObject
|| $key instanceof TextStringObject
|| $key instanceof IndefiniteLengthTextStringObject;
}
/**
* A tag number is the argument of a major type 6 head: the additional information carries it directly below 24,
* and announces its width above.
*/
private static function tagNumber(int $additionalInformation, ?string $data, string $name): int
{
if ($additionalInformation < 24) {
return $additionalInformation;
}
$width = match ($additionalInformation) {
CBORObject::LENGTH_1_BYTE => 1,
CBORObject::LENGTH_2_BYTES => 2,
CBORObject::LENGTH_4_BYTES => 4,
CBORObject::LENGTH_8_BYTES => 8,
default => throw new InvalidArgumentException(sprintf(
'Not a valid %s object. The additional information %d is not a valid CBOR tag head.',
$name,
$additionalInformation
)),
};
if ($data === null || strlen($data) !== $width) {
throw new InvalidArgumentException(sprintf(
'Not a valid %s object. The CBOR tag head announces %d byte(s) of tag number.',
$name,
$width
));
}
$number = 0;
for ($i = 0; $i < $width; ++$i) {
$number = ($number << 8) | ord($data[$i]);
}
if ($number < 0) {
throw new InvalidArgumentException(sprintf(
'Not a valid %s object. The CBOR tag number exceeds the platform integer range.',
$name
));
}
return $number;
}
}