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