diff --git a/.github/stale.yml b/.github/stale.yml index 3c84124d..19367a6a 100644 --- a/.github/stale.yml +++ b/.github/stale.yml @@ -1,4 +1,4 @@ -daysUntilStale: 60 +daysUntilStale: 30 daysUntilClose: 7 staleLabel: wontfix markComment: > diff --git a/Makefile b/Makefile index 78a5737d..ee687b18 100644 --- a/Makefile +++ b/Makefile @@ -18,7 +18,7 @@ st: vendor ## Run static analyse ################################################ ci-mu: vendor ## Mutation tests (for Github only) - vendor/bin/infection --logger-github -s --threads=$(nproc) --min-msi=40 --min-covered-msi=40 + vendor/bin/infection --logger-github -s --threads=$(nproc) --min-msi=80 --min-covered-msi=80 .PHONY: ci-cc ci-cc: vendor ## Show test coverage rates (for CI/CD only) diff --git a/composer.json b/composer.json index 3cfd1cf2..9ccd346a 100644 --- a/composer.json +++ b/composer.json @@ -58,7 +58,7 @@ "phpstan/phpstan-deprecation-rules": "^1.0", "phpstan/phpstan-phpunit": "^1.1", "phpstan/phpstan-strict-rules": "^1.3", - "phpunit/phpunit": "^9.0", + "phpunit/phpunit": "^9.5.5", "rector/rector": "^0.14", "roave/security-advisories": "dev-latest", "symfony/phpunit-bridge": "^6.1", diff --git a/src/ASN1/Component/Identifier.php b/src/ASN1/Component/Identifier.php index acf588f5..8646e176 100644 --- a/src/ASN1/Component/Identifier.php +++ b/src/ASN1/Component/Identifier.php @@ -103,7 +103,7 @@ public static function fromDER(string $data, int &$offset = null): self $tag = (0b00011111 & $byte); // long-form identifier if ($tag === 0x1f) { - $tag = self::_decodeLongFormTag($data, $idx); + $tag = self::decodeLongFormTag($data, $idx); } if (isset($offset)) { $offset = $idx; @@ -256,7 +256,7 @@ public static function classToName(int $class): string * * @return BigInteger Tag number */ - private static function _decodeLongFormTag(string $data, int &$offset): BigInteger + private static function decodeLongFormTag(string $data, int &$offset): BigInteger { $datalen = mb_strlen($data, '8bit'); $tag = BigInteger::of(0); diff --git a/src/ASN1/Component/Length.php b/src/ASN1/Component/Length.php index 0fca3908..47b73e6e 100644 --- a/src/ASN1/Component/Length.php +++ b/src/ASN1/Component/Length.php @@ -68,7 +68,7 @@ public static function fromDER(string $data, int &$offset = null): self if ($idx + $length > $datalen) { throw new DecodeException('Unexpected end of data while decoding long form length.'); } - $length = self::_decodeLongFormLength($length, $data, $idx); + $length = self::decodeLongFormLength($length, $data, $idx); } } if (isset($offset)) { @@ -186,7 +186,7 @@ public function isIndefinite(): bool * @param string $data Data * @param int $offset reference to the variable containing offset to the data */ - private static function _decodeLongFormLength(int $length, string $data, int &$offset): BigInteger + private static function decodeLongFormLength(int $length, string $data, int &$offset): BigInteger { // first octet must not be 0xff (spec 8.1.3.5c) if ($length === 127) { diff --git a/src/ASN1/DERData.php b/src/ASN1/DERData.php index a98580c8..6d4355df 100644 --- a/src/ASN1/DERData.php +++ b/src/ASN1/DERData.php @@ -20,28 +20,28 @@ final class DERData extends Element /** * DER encoded data. */ - protected string $_der; + private readonly string $der; /** * Identifier of the underlying type. */ - protected Identifier $_identifier; + private readonly Identifier $identifier; /** * Offset to the content in DER data. */ - protected int $_contentOffset = 0; + private int $contentOffset = 0; /** * @param string $data DER encoded data */ private function __construct(string $data) { - $this->_identifier = Identifier::fromDER($data, $this->_contentOffset); + $this->identifier = Identifier::fromDER($data, $this->contentOffset); // check that length encoding is valid - Length::expectFromDER($data, $this->_contentOffset); - $this->_der = $data; - parent::__construct($this->_identifier->intTag()); + Length::expectFromDER($data, $this->contentOffset); + $this->der = $data; + parent::__construct($this->identifier->intTag()); } public static function create(string $data): self @@ -51,26 +51,26 @@ public static function create(string $data): self public function typeClass(): int { - return $this->_identifier->typeClass(); + return $this->identifier->typeClass(); } public function isConstructed(): bool { - return $this->_identifier->isConstructed(); + return $this->identifier->isConstructed(); } public function toDER(): string { - return $this->_der; + return $this->der; } protected function encodedAsDER(): string { // if there's no content payload - if (mb_strlen($this->_der, '8bit') === $this->_contentOffset) { + if (mb_strlen($this->der, '8bit') === $this->contentOffset) { return ''; } - return mb_substr($this->_der, $this->_contentOffset, null, '8bit'); + return mb_substr($this->der, $this->contentOffset, null, '8bit'); } protected static function decodeFromDER(Identifier $identifier, string $data, int &$offset): ElementBase diff --git a/src/ASN1/Element.php b/src/ASN1/Element.php index 49075118..6b6d776b 100644 --- a/src/ASN1/Element.php +++ b/src/ASN1/Element.php @@ -218,11 +218,11 @@ abstract class Element implements ElementBase ]; /** - * @param bool $_indefiniteLength Whether type shall be encoded with indefinite length. + * @param bool $indefiniteLength Whether type shall be encoded with indefinite length. */ protected function __construct( - protected int $typeTag, - protected bool $_indefiniteLength = false + protected readonly int $typeTag, + protected bool $indefiniteLength = false ) { } @@ -245,7 +245,7 @@ public static function fromDER(string $data, int &$offset = null): static // decode identifier $identifier = Identifier::fromDER($data, $idx); // determine class that implements type specific decoding - $cls = self::_determineImplClass($identifier); + $cls = self::determineImplClass($identifier); // decode remaining element $element = $cls::decodeFromDER($identifier, $data, $idx); // if called in the context of a concrete class, check @@ -271,7 +271,7 @@ public function toDER(): string $this->typeTag ); $content = $this->encodedAsDER(); - if ($this->_indefiniteLength) { + if ($this->indefiniteLength) { $length = Length::create(0, true); $eoc = EOC::create(); return $identifier->toDER() . $length->toDER() . $content . $eoc->toDER(); @@ -293,16 +293,16 @@ public function isType(int $tag): bool } // negative tags identify an abstract pseudotype if ($tag < 0) { - return $this->_isPseudoType($tag); + return $this->isPseudoType($tag); } - return $this->_isConcreteType($tag); + return $this->isConcreteType($tag); } public function expectType(int $tag): ElementBase { if (! $this->isType($tag)) { throw new UnexpectedValueException( - sprintf('%s expected, got %s.', self::tagToName($tag), $this->_typeDescriptorString()) + sprintf('%s expected, got %s.', self::tagToName($tag), $this->typeDescriptorString()) ); } return $this; @@ -331,7 +331,7 @@ public function expectTagged(?int $tag = null): TaggedType */ public function hasIndefiniteLength(): bool { - return $this->_indefiniteLength; + return $this->indefiniteLength; } /** @@ -342,7 +342,7 @@ public function hasIndefiniteLength(): bool public function withIndefiniteLength(bool $indefinite = true): self { $obj = clone $this; - $obj->_indefiniteLength = $indefinite; + $obj->indefiniteLength = $indefinite; return $obj; } @@ -391,11 +391,11 @@ abstract protected static function decodeFromDER(Identifier $identifier, string * * @return string Class name */ - protected static function _determineImplClass(Identifier $identifier): string + protected static function determineImplClass(Identifier $identifier): string { switch ($identifier->typeClass()) { case Identifier::CLASS_UNIVERSAL: - $cls = self::_determineUniversalImplClass($identifier->intTag()); + $cls = self::determineUniversalImplClass($identifier->intTag()); // constructed strings may be present in BER if ($identifier->isConstructed() && is_subclass_of($cls, StringType::class)) { @@ -421,7 +421,7 @@ protected static function _determineImplClass(Identifier $identifier): string * * @return string Class name */ - protected static function _determineUniversalImplClass(int $tag): string + protected static function determineUniversalImplClass(int $tag): string { if (! array_key_exists($tag, self::MAP_TAG_TO_CLASS)) { throw new UnexpectedValueException("Universal tag {$tag} not implemented."); @@ -432,7 +432,7 @@ protected static function _determineUniversalImplClass(int $tag): string /** * Get textual description of the type for debugging purposes. */ - protected function _typeDescriptorString(): string + protected function typeDescriptorString(): string { if ($this->typeClass() === Identifier::CLASS_UNIVERSAL) { return self::tagToName($this->typeTag); @@ -441,9 +441,9 @@ protected function _typeDescriptorString(): string } /** - * Check whether the element is a concrete type of a given tag. + * Check whether the element is a concrete type of given tag. */ - private function _isConcreteType(int $tag): bool + private function isConcreteType(int $tag): bool { // if tag doesn't match if ($this->tag() !== $tag) { @@ -451,7 +451,7 @@ private function _isConcreteType(int $tag): bool } // if type is universal check that instance is of a correct class if ($this->typeClass() === Identifier::CLASS_UNIVERSAL) { - $cls = self::_determineUniversalImplClass($tag); + $cls = self::determineUniversalImplClass($tag); if (! $this instanceof $cls) { return false; } @@ -462,7 +462,7 @@ private function _isConcreteType(int $tag): bool /** * Check whether the element is a pseudotype. */ - private function _isPseudoType(int $tag): bool + private function isPseudoType(int $tag): bool { return match ($tag) { self::TYPE_STRING => $this instanceof StringType, diff --git a/src/ASN1/Type/BaseString.php b/src/ASN1/Type/BaseString.php index 964d8206..34cae98b 100644 --- a/src/ASN1/Type/BaseString.php +++ b/src/ASN1/Type/BaseString.php @@ -16,15 +16,15 @@ abstract class BaseString extends Element implements StringType, Stringable /** * String value. */ - protected string $_string; + private readonly string $string; - public function __construct(int $typeTag, string $string) + protected function __construct(int $typeTag, string $string) { parent::__construct($typeTag); - if (! $this->_validateString($string)) { + if (! $this->validateString($string)) { throw new InvalidArgumentException(sprintf('Not a valid %s string.', self::tagToName($this->typeTag))); } - $this->_string = $string; + $this->string = $string; } public function __toString(): string @@ -37,13 +37,18 @@ public function __toString(): string */ public function string(): string { - return $this->_string; + return $this->string; + } + + protected function encodedAsDER(): string + { + return $this->string; } /** * Check whether string is valid for the concrete type. */ - protected function _validateString(string $string): bool + protected function validateString(string $string): bool { // Override in derived classes return true; diff --git a/src/ASN1/Type/BaseTime.php b/src/ASN1/Type/BaseTime.php index b589b8bf..61b4e116 100644 --- a/src/ASN1/Type/BaseTime.php +++ b/src/ASN1/Type/BaseTime.php @@ -20,9 +20,9 @@ abstract class BaseTime extends Element implements TimeType, Stringable */ public const TZ_UTC = 'UTC'; - public function __construct( + protected function __construct( int $typeTag, - protected readonly DateTimeImmutable $_dateTime + protected readonly DateTimeImmutable $dateTime ) { parent::__construct($typeTag); } @@ -46,7 +46,7 @@ abstract public static function fromString(string $time): static; */ public function dateTime(): DateTimeImmutable { - return $this->_dateTime; + return $this->dateTime; } /** diff --git a/src/ASN1/Type/Constructed/ConstructedString.php b/src/ASN1/Type/Constructed/ConstructedString.php index 8fcf0a81..0ed66412 100644 --- a/src/ASN1/Type/Constructed/ConstructedString.php +++ b/src/ASN1/Type/Constructed/ConstructedString.php @@ -150,7 +150,7 @@ protected static function decodeIndefiniteLength(int $typeTag, string $data, int } $offset = $idx; $type = self::createWithTag($typeTag, ...$elements); - $type->_indefiniteLength = true; + $type->indefiniteLength = true; return $type; } } diff --git a/src/ASN1/Type/Constructed/Sequence.php b/src/ASN1/Type/Constructed/Sequence.php index f96c14f3..8072f90a 100644 --- a/src/ASN1/Type/Constructed/Sequence.php +++ b/src/ASN1/Type/Constructed/Sequence.php @@ -86,7 +86,7 @@ protected static function decodeIndefiniteLength(string $data, int &$offset): se } $offset = $idx; $type = self::create(...$elements); - $type->_indefiniteLength = true; + $type->indefiniteLength = true; return $type; } } diff --git a/src/ASN1/Type/Constructed/Set.php b/src/ASN1/Type/Constructed/Set.php index ec244fea..dadce1b4 100644 --- a/src/ASN1/Type/Constructed/Set.php +++ b/src/ASN1/Type/Constructed/Set.php @@ -129,7 +129,7 @@ protected static function decodeIndefiniteLength(string $data, int &$offset): El } $offset = $idx; $type = self::create(...$elements); - $type->_indefiniteLength = true; + $type->indefiniteLength = true; return $type; } } diff --git a/src/ASN1/Type/Primitive/BMPString.php b/src/ASN1/Type/Primitive/BMPString.php index 963fd532..79dcb41a 100644 --- a/src/ASN1/Type/Primitive/BMPString.php +++ b/src/ASN1/Type/Primitive/BMPString.php @@ -27,7 +27,7 @@ public static function create(string $string): self return new self($string); } - protected function _validateString(string $string): bool + protected function validateString(string $string): bool { // UCS-2 has fixed with of 2 octets (16 bits) return mb_strlen($string, '8bit') % 2 === 0; diff --git a/src/ASN1/Type/Primitive/BitString.php b/src/ASN1/Type/Primitive/BitString.php index d9967ba9..1ef5073a 100644 --- a/src/ASN1/Type/Primitive/BitString.php +++ b/src/ASN1/Type/Primitive/BitString.php @@ -27,11 +27,11 @@ final class BitString extends BaseString /** * @param string $string Content octets - * @param int $_unusedBits Number of unused bits in the last octet + * @param int $unusedBits Number of unused bits in the last octet */ private function __construct( string $string, - protected int $_unusedBits = 0 + private readonly int $unusedBits = 0 ) { parent::__construct(self::TYPE_BIT_STRING, $string); } @@ -46,7 +46,7 @@ public static function create(string $string, int $_unusedBits = 0): self */ public function numBits(): int { - return mb_strlen($this->_string, '8bit') * 8 - $this->_unusedBits; + return mb_strlen($this->string(), '8bit') * 8 - $this->unusedBits; } /** @@ -54,7 +54,7 @@ public function numBits(): int */ public function unusedBits(): int { - return $this->_unusedBits; + return $this->unusedBits; } /** @@ -67,18 +67,18 @@ public function testBit(int $idx): bool // octet index $oi = (int) floor($idx / 8); // if octet is outside range - if ($oi < 0 || $oi >= mb_strlen($this->_string, '8bit')) { + if ($oi < 0 || $oi >= mb_strlen($this->string(), '8bit')) { throw new OutOfBoundsException('Index is out of bounds.'); } // bit index $bi = $idx % 8; // if tested bit is last octet's unused bit - if ($oi === mb_strlen($this->_string, '8bit') - 1) { - if ($bi >= 8 - $this->_unusedBits) { + if ($oi === mb_strlen($this->string(), '8bit') - 1) { + if ($bi >= 8 - $this->unusedBits) { throw new OutOfBoundsException('Index refers to an unused bit.'); } } - $byte = $this->_string[$oi]; + $byte = $this->string()[$oi]; // index 0 is the most significant bit in byte $mask = 0x01 << (7 - $bi); return (ord($byte) & $mask) > 0; @@ -120,10 +120,10 @@ public function range(int $start, int $length): string public function withoutTrailingZeroes(): self { // if bit string was empty - if ($this->_string === '') { + if ($this->string() === '') { return self::create(''); } - $bits = $this->_string; + $bits = $this->string(); // count number of empty trailing octets $unused_octets = 0; for ($idx = mb_strlen($bits, '8bit') - 1; $idx >= 0; --$idx, ++$unused_octets) { @@ -151,12 +151,12 @@ public function withoutTrailingZeroes(): self protected function encodedAsDER(): string { - $der = chr($this->_unusedBits); - $der .= $this->_string; - if ($this->_unusedBits !== 0) { + $der = chr($this->unusedBits); + $der .= $this->string(); + if ($this->unusedBits !== 0) { $octet = $der[mb_strlen($der, '8bit') - 1]; // set unused bits to zero - $octet &= chr(0xff & ~((1 << $this->_unusedBits) - 1)); + $octet &= chr(0xff & ~((1 << $this->unusedBits) - 1)); $der[mb_strlen($der, '8bit') - 1] = $octet; } return $der; diff --git a/src/ASN1/Type/Primitive/EOC.php b/src/ASN1/Type/Primitive/EOC.php index 453ffb05..cc333164 100644 --- a/src/ASN1/Type/Primitive/EOC.php +++ b/src/ASN1/Type/Primitive/EOC.php @@ -44,6 +44,6 @@ protected static function decodeFromDER(Identifier $identifier, string $data, in // EOC type has always zero length Length::expectFromDER($data, $idx, 0); $offset = $idx; - return new self(); + return self::create(); } } diff --git a/src/ASN1/Type/Primitive/GeneralString.php b/src/ASN1/Type/Primitive/GeneralString.php index 389b53b9..a3ae69a0 100644 --- a/src/ASN1/Type/Primitive/GeneralString.php +++ b/src/ASN1/Type/Primitive/GeneralString.php @@ -24,7 +24,7 @@ public static function create(string $string): self return new self($string); } - protected function _validateString(string $string): bool + protected function validateString(string $string): bool { // allow everything return true; diff --git a/src/ASN1/Type/Primitive/GeneralizedTime.php b/src/ASN1/Type/Primitive/GeneralizedTime.php index 4f29c8a1..cd52cc5d 100644 --- a/src/ASN1/Type/Primitive/GeneralizedTime.php +++ b/src/ASN1/Type/Primitive/GeneralizedTime.php @@ -69,13 +69,13 @@ public static function create(DateTimeImmutable $dt): self public static function fromString(string $time, ?string $tz = null): static { - return new static(new DateTimeImmutable($time, self::_createTimeZone($tz))); + return new static(new DateTimeImmutable($time, self::createTimeZone($tz))); } protected function encodedAsDER(): string { if (! isset($this->_formatted)) { - $dt = $this->_dateTime->setTimezone(new DateTimeZone('UTC')); + $dt = $this->dateTime->setTimezone(new DateTimeZone('UTC')); $this->_formatted = $dt->format('YmdHis'); // if fractions were used $frac = $dt->format('u'); @@ -116,13 +116,13 @@ protected static function decodeFromDER(Identifier $identifier, string $data, in throw new DecodeException('Failed to decode GeneralizedTime'); } $offset = $idx; - return new self($dt); + return self::create($dt); } /** * Create `DateTimeZone` object from string. */ - private static function _createTimeZone(?string $tz): DateTimeZone + private static function createTimeZone(?string $tz): DateTimeZone { try { return new DateTimeZone($tz ?? 'UTC'); diff --git a/src/ASN1/Type/Primitive/GraphicString.php b/src/ASN1/Type/Primitive/GraphicString.php index bacb687e..7fba4155 100644 --- a/src/ASN1/Type/Primitive/GraphicString.php +++ b/src/ASN1/Type/Primitive/GraphicString.php @@ -24,7 +24,7 @@ public static function create(string $string): self return new self($string); } - protected function _validateString(string $string): bool + protected function validateString(string $string): bool { // allow everything return true; diff --git a/src/ASN1/Type/Primitive/IA5String.php b/src/ASN1/Type/Primitive/IA5String.php index 29879d57..7f394148 100644 --- a/src/ASN1/Type/Primitive/IA5String.php +++ b/src/ASN1/Type/Primitive/IA5String.php @@ -24,7 +24,7 @@ public static function create(string $string): self return new self($string); } - protected function _validateString(string $string): bool + protected function validateString(string $string): bool { return preg_match('/[^\x00-\x7f]/', $string) !== 1; } diff --git a/src/ASN1/Type/Primitive/Integer.php b/src/ASN1/Type/Primitive/Integer.php index 257a902d..c2f58b3c 100644 --- a/src/ASN1/Type/Primitive/Integer.php +++ b/src/ASN1/Type/Primitive/Integer.php @@ -37,7 +37,7 @@ class Integer extends Element final protected function __construct(BigInteger|int|string $number, int $typeTag) { parent::__construct($typeTag); - if (! self::_validateNumber($number)) { + if (! self::validateNumber($number)) { $var = is_scalar($number) ? (string) $number : gettype($number); throw new InvalidArgumentException("'{$var}' is not a valid number."); } @@ -92,7 +92,7 @@ protected static function decodeFromDER(Identifier $identifier, string $data, in /** * Test that number is valid for this context. */ - private static function _validateNumber(mixed $num): bool + private static function validateNumber(mixed $num): bool { if (is_int($num)) { return true; diff --git a/src/ASN1/Type/Primitive/NullType.php b/src/ASN1/Type/Primitive/NullType.php index 7683505b..66f1671e 100644 --- a/src/ASN1/Type/Primitive/NullType.php +++ b/src/ASN1/Type/Primitive/NullType.php @@ -44,6 +44,6 @@ protected static function decodeFromDER(Identifier $identifier, string $data, in // null type has always zero length Length::expectFromDER($data, $idx, 0); $offset = $idx; - return new self(); + return self::create(); } } diff --git a/src/ASN1/Type/Primitive/NumericString.php b/src/ASN1/Type/Primitive/NumericString.php index c77cff6a..d48d4cc7 100644 --- a/src/ASN1/Type/Primitive/NumericString.php +++ b/src/ASN1/Type/Primitive/NumericString.php @@ -24,7 +24,7 @@ public static function create(string $string): self return new self($string); } - protected function _validateString(string $string): bool + protected function validateString(string $string): bool { return preg_match('/[^\d ]/', $string) !== 1; } diff --git a/src/ASN1/Type/Primitive/ObjectDescriptor.php b/src/ASN1/Type/Primitive/ObjectDescriptor.php index b2246cca..f7338a63 100644 --- a/src/ASN1/Type/Primitive/ObjectDescriptor.php +++ b/src/ASN1/Type/Primitive/ObjectDescriptor.php @@ -29,6 +29,6 @@ public static function create(string $descriptor): self */ public function descriptor(): string { - return $this->_string; + return $this->string(); } } diff --git a/src/ASN1/Type/Primitive/ObjectIdentifier.php b/src/ASN1/Type/Primitive/ObjectIdentifier.php index 2b6b9964..99f1853a 100644 --- a/src/ASN1/Type/Primitive/ObjectIdentifier.php +++ b/src/ASN1/Type/Primitive/ObjectIdentifier.php @@ -34,37 +34,37 @@ final class ObjectIdentifier extends Element * * @var BigInteger[] */ - protected array $_subids; + private readonly array $subids; /** - * @param string $_oid OID in dotted format + * @param string $oid OID in dotted format */ private function __construct( - private readonly string $_oid, - ?int $typeTag = null + private readonly string $oid, + ?int $typeTag ) { - $this->_subids = self::_explodeDottedOID($_oid); + $this->subids = self::explodeDottedOID($oid); // if OID is non-empty - if (count($this->_subids) > 0) { + if (count($this->subids) > 0) { // check that at least two nodes are set - if (count($this->_subids) < 2) { + if (count($this->subids) < 2) { throw new UnexpectedValueException('OID must have at least two nodes.'); } // check that root arc is in 0..2 range - if ($this->_subids[0]->isGreaterThan(2)) { + if ($this->subids[0]->isGreaterThan(2)) { throw new UnexpectedValueException('Root arc must be in range of 0..2.'); } // if root arc is 0 or 1, second node must be in 0..39 range - if ($this->_subids[0]->isLessThan(2) && $this->_subids[1]->isGreaterThanOrEqualTo(40)) { + if ($this->subids[0]->isLessThan(2) && $this->subids[1]->isGreaterThanOrEqualTo(40)) { throw new UnexpectedValueException('Second node must be in 0..39 range for root arcs 0 and 1.'); } } parent::__construct($typeTag ?? self::TYPE_OBJECT_IDENTIFIER); } - public static function create(string $_oid, ?int $typeTag = null): self + public static function create(string $oid, ?int $typeTag = null): self { - return new self($_oid, $typeTag); + return new self($oid, $typeTag); } /** @@ -72,25 +72,25 @@ public static function create(string $_oid, ?int $typeTag = null): self */ public function oid(): string { - return $this->_oid; + return $this->oid; } protected function encodedAsDER(): string { - $subids = $this->_subids; + $subids = $this->subids; // encode first two subids to one according to spec section 8.19.4 if (count($subids) >= 2) { $num = $subids[0]->multipliedBy(40)->plus($subids[1]); array_splice($subids, 0, 2, [$num]); } - return self::_encodeSubIDs(...$subids); + return self::encodeSubIDs(...$subids); } protected static function decodeFromDER(Identifier $identifier, string $data, int &$offset): ElementBase { $idx = $offset; $len = Length::expectFromDER($data, $idx)->intLength(); - $subids = self::_decodeSubIDs(mb_substr($data, $idx, $len, '8bit')); + $subids = self::decodeSubIDs(mb_substr($data, $idx, $len, '8bit')); $idx += $len; // decode first subidentifier according to spec section 8.19.4 if (isset($subids[0])) { @@ -103,7 +103,7 @@ protected static function decodeFromDER(Identifier $identifier, string $data, in array_splice($subids, 0, 1, [$x, $y]); } $offset = $idx; - return new self(self::_implodeSubIDs(...$subids)); + return self::create(self::implodeSubIDs(...$subids)); } /** @@ -113,7 +113,7 @@ protected static function decodeFromDER(Identifier $identifier, string $data, in * * @return BigInteger[] Array of BigInteger numbers */ - protected static function _explodeDottedOID(string $oid): array + protected static function explodeDottedOID(string $oid): array { $subids = []; if ($oid !== '') { @@ -132,7 +132,7 @@ protected static function _explodeDottedOID(string $oid): array /** * Implode an array of sub IDs to dotted OID format. */ - protected static function _implodeSubIDs(BigInteger ...$subids): string + protected static function implodeSubIDs(BigInteger ...$subids): string { return implode('.', array_map(static fn ($num) => $num->toBase(10), $subids)); } @@ -140,7 +140,7 @@ protected static function _implodeSubIDs(BigInteger ...$subids): string /** * Encode sub ID's to DER. */ - protected static function _encodeSubIDs(BigInteger ...$subids): string + protected static function encodeSubIDs(BigInteger ...$subids): string { $data = ''; foreach ($subids as $subid) { @@ -172,7 +172,7 @@ protected static function _encodeSubIDs(BigInteger ...$subids): string * * @return BigInteger[] Array of BigInteger numbers */ - protected static function _decodeSubIDs(string $data): array + protected static function decodeSubIDs(string $data): array { $subids = []; $idx = 0; diff --git a/src/ASN1/Type/Primitive/PrintableString.php b/src/ASN1/Type/Primitive/PrintableString.php index a5fd114a..10f3170e 100644 --- a/src/ASN1/Type/Primitive/PrintableString.php +++ b/src/ASN1/Type/Primitive/PrintableString.php @@ -24,7 +24,7 @@ public static function create(string $string): self return new self($string); } - protected function _validateString(string $string): bool + protected function validateString(string $string): bool { $chars = preg_quote(" '()+,-./:=?]", '/'); return preg_match('/[^A-Za-z0-9' . $chars . ']/', $string) !== 1; diff --git a/src/ASN1/Type/Primitive/Real.php b/src/ASN1/Type/Primitive/Real.php index 2419ff6c..28d08421 100644 --- a/src/ASN1/Type/Primitive/Real.php +++ b/src/ASN1/Type/Primitive/Real.php @@ -160,13 +160,13 @@ public static function create( public static function fromFloat(float $number): self { if (is_infinite($number)) { - return self::_fromInfinite($number); + return self::fromInfinite($number); } if (is_nan($number)) { throw new UnexpectedValueException('NaN values not supported.'); } - [$m, $e] = self::_parse754Double(pack('E', $number)); - return new self($m, $e, 2); + [$m, $e] = self::parse754Double(pack('E', $number)); + return self::create($m, $e, 2); } /** @@ -176,8 +176,8 @@ public static function fromFloat(float $number): self */ public static function fromString(string $number): self { - [$m, $e] = self::_parseString($number); - return new self($m, $e, 10); + [$m, $e] = self::parseString($number); + return self::create($m, $e, 10); } /** @@ -236,7 +236,7 @@ public function nr3Val(): string { // convert to base 10 if ($this->_base === 2) { - [$m, $e] = self::_parseString(sprintf('%15E', $this->floatVal())); + [$m, $e] = self::parseString(sprintf('%15E', $this->floatVal())); } else { $m = $this->_mantissa->getValue(); $e = $this->_exponent->getValue(); @@ -264,7 +264,7 @@ protected function encodedAsDER(): string { $infExponent = BigInteger::of(self::INF_EXPONENT); if ($this->_exponent->getValue()->isEqualTo($infExponent)) { - return $this->_encodeSpecial(); + return $this->encodeSpecial(); } // if the real value is the value zero, there shall be no contents // octets in the encoding. (X.690 07-2002, section 8.5.2) @@ -272,20 +272,20 @@ protected function encodedAsDER(): string return ''; } if ($this->_base === 10) { - return $this->_encodeDecimal(); + return $this->encodeDecimal(); } - return $this->_encodeBinary(); + return $this->encodeBinary(); } /** * Encode in binary format. */ - protected function _encodeBinary(): string + protected function encodeBinary(): string { /** @var BigInteger $m */ /** @var BigInteger $e */ /** @var int $sign */ - [$base, $sign, $m, $e] = $this->_prepareBinaryEncoding(); + [$base, $sign, $m, $e] = $this->prepareBinaryEncoding(); $zero = BigInteger::of(0); $byte = 0x80; if ($sign < 0) { @@ -342,7 +342,7 @@ protected function _encodeBinary(): string /** * Encode in decimal format. */ - protected function _encodeDecimal(): string + protected function encodeDecimal(): string { // encode in NR3 decimal encoding return chr(0x03) . $this->nr3Val(); @@ -351,7 +351,7 @@ protected function _encodeDecimal(): string /** * Encode special value. */ - protected function _encodeSpecial(): string + protected function encodeSpecial(): string { return match ($this->_mantissa->toInt()) { 1 => chr(0x40), @@ -366,16 +366,16 @@ protected static function decodeFromDER(Identifier $identifier, string $data, in $length = Length::expectFromDER($data, $idx)->intLength(); // if length is zero, value is zero (spec 8.5.2) if ($length === 0) { - $obj = new self(0, 0, 10); + $obj = self::create(0, 0, 10); } else { $bytes = mb_substr($data, $idx, $length, '8bit'); $byte = ord($bytes[0]); if ((0x80 & $byte) !== 0) { // bit 8 = 1 - $obj = self::_decodeBinaryEncoding($bytes); + $obj = self::decodeBinaryEncoding($bytes); } elseif ($byte >> 6 === 0x00) { // bit 8 = 0, bit 7 = 0 - $obj = self::_decodeDecimalEncoding($bytes); + $obj = self::decodeDecimalEncoding($bytes); } else { // bit 8 = 0, bit 7 = 1 - $obj = self::_decodeSpecialRealValue($bytes); + $obj = self::decodeSpecialRealValue($bytes); } } $offset = $idx + $length; @@ -385,7 +385,7 @@ protected static function decodeFromDER(Identifier $identifier, string $data, in /** * Decode binary encoding. */ - protected static function _decodeBinaryEncoding(string $data): self + protected static function decodeBinaryEncoding(string $data): self { $byte = ord($data[0]); // bit 7 is set if mantissa is negative @@ -430,13 +430,13 @@ protected static function _decodeBinaryEncoding(string $data): self if ($neg) { $n = $n->negated(); } - return new self($n, $exp, 2); + return self::create($n, $exp, 2); } /** * Decode decimal encoding. */ - protected static function _decodeDecimalEncoding(string $data): self + protected static function decodeDecimalEncoding(string $data): self { $nr = ord($data[0]) & 0x3f; if (! in_array($nr, [1, 2, 3], true)) { @@ -449,17 +449,17 @@ protected static function _decodeDecimalEncoding(string $data): self /** * Decode special encoding. */ - protected static function _decodeSpecialRealValue(string $data): self + protected static function decodeSpecialRealValue(string $data): self { if (mb_strlen($data, '8bit') !== 1) { throw new DecodeException('SpecialRealValue must have one content octet.'); } $byte = ord($data[0]); if ($byte === 0x40) { // positive infinity - return self::_fromInfinite(INF); + return self::fromInfinite(INF); } if ($byte === 0x41) { // negative infinity - return self::_fromInfinite(-INF); + return self::fromInfinite(-INF); } throw new DecodeException('Invalid SpecialRealValue encoding.'); } @@ -469,7 +469,7 @@ protected static function _decodeSpecialRealValue(string $data): self * * @return array (int) base, (int) sign, (BigInteger) mantissa and (BigInteger) exponent */ - protected function _prepareBinaryEncoding(): array + protected function prepareBinaryEncoding(): array { $base = 2; $m = $this->_mantissa->getValue(); @@ -497,9 +497,9 @@ protected function _prepareBinaryEncoding(): array /** * Initialize from INF or -INF. */ - private static function _fromInfinite(float $inf): self + private static function fromInfinite(float $inf): self { - return new self($inf === -INF ? -1 : 1, self::INF_EXPONENT, 2); + return self::create($inf === -INF ? -1 : 1, self::INF_EXPONENT, 2); } /** @@ -509,7 +509,7 @@ private static function _fromInfinite(float $inf): self * * @return BigInteger[] Tuple of mantissa and exponent */ - private static function _parse754Double(string $octets): array + private static function parse754Double(string $octets): array { $n = BigInteger::fromBytes($octets, false); // sign bit @@ -560,20 +560,20 @@ private static function _parse754Double(string $octets): array * * @return BigInteger[] Tuple of mantissa and exponent */ - private static function _parseString(string $str): array + private static function parseString(string $str): array { // PHP exponent format if (preg_match(self::PHP_EXPONENT_DNUM, $str, $match) === 1) { - [$m, $e] = self::_parsePHPExponentMatch($match); + [$m, $e] = self::parsePHPExponentMatch($match); } // NR3 format elseif (preg_match(self::NR3_REGEX, $str, $match) === 1) { - [$m, $e] = self::_parseNR3Match($match); + [$m, $e] = self::parseNR3Match($match); } // NR2 format elseif (preg_match(self::NR2_REGEX, $str, $match) === 1) { - [$m, $e] = self::_parseNR2Match($match); + [$m, $e] = self::parseNR2Match($match); } // NR1 format elseif (preg_match(self::NR1_REGEX, $str, $match) === 1) { - [$m, $e] = self::_parseNR1Match($match); + [$m, $e] = self::parseNR1Match($match); } // invalid number else { throw new UnexpectedValueException("{$str} could not be parsed to REAL."); @@ -595,7 +595,7 @@ private static function _parseString(string $str): array * * @return BigInteger[] Tuple of mantissa and exponent */ - private static function _parsePHPExponentMatch(array $match): array + private static function parsePHPExponentMatch(array $match): array { // mantissa sign $ms = $match['ms'] === '-' ? -1 : 1; @@ -623,7 +623,7 @@ private static function _parsePHPExponentMatch(array $match): array * * @return BigInteger[] Tuple of mantissa and exponent */ - private static function _parseNR3Match(array $match): array + private static function parseNR3Match(array $match): array { // mantissa sign $ms = $match['ms'] === '-' ? -1 : 1; @@ -653,7 +653,7 @@ private static function _parseNR3Match(array $match): array * * @return BigInteger[] Tuple of mantissa and exponent */ - private static function _parseNR2Match(array $match): array + private static function parseNR2Match(array $match): array { $sign = $match['s'] === '-' ? -1 : 1; // explode decimal number to integer and fraction parts @@ -679,7 +679,7 @@ private static function _parseNR2Match(array $match): array * * @return BigInteger[] Tuple of mantissa and exponent */ - private static function _parseNR1Match(array $match): array + private static function parseNR1Match(array $match): array { $sign = $match['s'] === '-' ? -1 : 1; $int = ltrim($match['i'], '0'); diff --git a/src/ASN1/Type/Primitive/RelativeOID.php b/src/ASN1/Type/Primitive/RelativeOID.php index 29df3466..67e44e9f 100644 --- a/src/ASN1/Type/Primitive/RelativeOID.php +++ b/src/ASN1/Type/Primitive/RelativeOID.php @@ -32,7 +32,7 @@ final class RelativeOID extends Element * * @var BigInteger[] */ - protected array $_subids; + private readonly array $subids; /** * @param string $oid OID in dotted format @@ -40,7 +40,7 @@ final class RelativeOID extends Element private function __construct(private readonly string $oid) { parent::__construct(self::TYPE_RELATIVE_OID); - $this->_subids = self::_explodeDottedOID($oid); + $this->subids = self::explodeDottedOID($oid); } public static function create(string $oid): self @@ -58,16 +58,16 @@ public function oid(): string protected function encodedAsDER(): string { - return self::_encodeSubIDs(...$this->_subids); + return self::encodeSubIDs(...$this->subids); } protected static function decodeFromDER(Identifier $identifier, string $data, int &$offset): ElementBase { $idx = $offset; $len = Length::expectFromDER($data, $idx)->intLength(); - $subids = self::_decodeSubIDs(mb_substr($data, $idx, $len, '8bit')); + $subids = self::decodeSubIDs(mb_substr($data, $idx, $len, '8bit')); $offset = $idx + $len; - return self::create(self::_implodeSubIDs(...$subids)); + return self::create(self::implodeSubIDs(...$subids)); } /** @@ -77,7 +77,7 @@ protected static function decodeFromDER(Identifier $identifier, string $data, in * * @return BigInteger[] Array of BigInteger numbers */ - protected static function _explodeDottedOID(string $oid): array + protected static function explodeDottedOID(string $oid): array { $subids = []; if ($oid !== '') { @@ -96,7 +96,7 @@ protected static function _explodeDottedOID(string $oid): array /** * Implode an array of sub IDs to dotted OID format. */ - protected static function _implodeSubIDs(BigInteger ...$subids): string + protected static function implodeSubIDs(BigInteger ...$subids): string { return implode('.', array_map(static fn ($num) => $num->toBase(10), $subids)); } @@ -104,7 +104,7 @@ protected static function _implodeSubIDs(BigInteger ...$subids): string /** * Encode sub ID's to DER. */ - protected static function _encodeSubIDs(BigInteger ...$subids): string + protected static function encodeSubIDs(BigInteger ...$subids): string { $data = ''; foreach ($subids as $subid) { @@ -136,7 +136,7 @@ protected static function _encodeSubIDs(BigInteger ...$subids): string * * @return BigInteger[] Array of BigInteger numbers */ - protected static function _decodeSubIDs(string $data): array + protected static function decodeSubIDs(string $data): array { $subids = []; $idx = 0; diff --git a/src/ASN1/Type/Primitive/T61String.php b/src/ASN1/Type/Primitive/T61String.php index 37051b2b..92ac2f29 100644 --- a/src/ASN1/Type/Primitive/T61String.php +++ b/src/ASN1/Type/Primitive/T61String.php @@ -24,7 +24,7 @@ public static function create(string $string): self return new self($string); } - protected function _validateString(string $string): bool + protected function validateString(string $string): bool { // allow everything since there's literally // thousands of allowed characters (16 bit composed characters) diff --git a/src/ASN1/Type/Primitive/UTCTime.php b/src/ASN1/Type/Primitive/UTCTime.php index eb1830c9..87e18fac 100644 --- a/src/ASN1/Type/Primitive/UTCTime.php +++ b/src/ASN1/Type/Primitive/UTCTime.php @@ -56,7 +56,7 @@ public static function fromString(string $time): static protected function encodedAsDER(): string { - $dt = $this->_dateTime->setTimezone(new DateTimeZone('UTC')); + $dt = $this->dateTime->setTimezone(new DateTimeZone('UTC')); return $dt->format('ymdHis\\Z'); } @@ -76,6 +76,6 @@ protected static function decodeFromDER(Identifier $identifier, string $data, in throw new DecodeException('Failed to decode UTCTime'); } $offset = $idx; - return new self($dt); + return self::create($dt); } } diff --git a/src/ASN1/Type/Primitive/UTF8String.php b/src/ASN1/Type/Primitive/UTF8String.php index c38505f7..8d40315a 100644 --- a/src/ASN1/Type/Primitive/UTF8String.php +++ b/src/ASN1/Type/Primitive/UTF8String.php @@ -26,7 +26,7 @@ public static function create(string $string): self return new self($string); } - protected function _validateString(string $string): bool + protected function validateString(string $string): bool { return mb_check_encoding($string, 'UTF-8'); } diff --git a/src/ASN1/Type/Primitive/UniversalString.php b/src/ASN1/Type/Primitive/UniversalString.php index 7687512c..6e74ac5b 100644 --- a/src/ASN1/Type/Primitive/UniversalString.php +++ b/src/ASN1/Type/Primitive/UniversalString.php @@ -27,7 +27,7 @@ public static function create(string $string): self return new self($string); } - protected function _validateString(string $string): bool + protected function validateString(string $string): bool { // UCS-4 has fixed with of 4 octets (32 bits) if (mb_strlen($string, '8bit') % 4 !== 0) { diff --git a/src/ASN1/Type/Primitive/VideotexString.php b/src/ASN1/Type/Primitive/VideotexString.php index 730eb51c..718932d1 100644 --- a/src/ASN1/Type/Primitive/VideotexString.php +++ b/src/ASN1/Type/Primitive/VideotexString.php @@ -24,7 +24,7 @@ public static function create(string $string): self return new self($string); } - protected function _validateString(string $string): bool + protected function validateString(string $string): bool { // allow everything return true; diff --git a/src/ASN1/Type/Primitive/VisibleString.php b/src/ASN1/Type/Primitive/VisibleString.php index 790d0ae4..9e51d1bd 100644 --- a/src/ASN1/Type/Primitive/VisibleString.php +++ b/src/ASN1/Type/Primitive/VisibleString.php @@ -24,7 +24,7 @@ public static function create(string $string): self return new self($string); } - protected function _validateString(string $string): bool + protected function validateString(string $string): bool { return preg_match('/[^\x20-\x7e]/', $string) !== 1; } diff --git a/src/ASN1/Type/PrimitiveString.php b/src/ASN1/Type/PrimitiveString.php index 6344a981..f1b45000 100644 --- a/src/ASN1/Type/PrimitiveString.php +++ b/src/ASN1/Type/PrimitiveString.php @@ -22,11 +22,6 @@ abstract class PrimitiveString extends BaseString abstract public static function create(string $string): self; - protected function encodedAsDER(): string - { - return $this->_string; - } - protected static function decodeFromDER(Identifier $identifier, string $data, int &$offset): static { $idx = $offset; diff --git a/src/ASN1/Type/Tagged/DERTaggedType.php b/src/ASN1/Type/Tagged/DERTaggedType.php index b3d460da..26a7c458 100644 --- a/src/ASN1/Type/Tagged/DERTaggedType.php +++ b/src/ASN1/Type/Tagged/DERTaggedType.php @@ -65,7 +65,7 @@ public function implicit(int $tag, int $class = Identifier::CLASS_UNIVERSAL): Un { $identifier = $this->_identifier->withClass($class) ->withTag($tag); - $cls = self::_determineImplClass($identifier); + $cls = self::determineImplClass($identifier); $idx = $this->_offset; /** @var ElementBase $element */ $element = $cls::decodeFromDER($identifier, $this->_data, $idx); diff --git a/src/ASN1/Type/Tagged/ExplicitlyTaggedType.php b/src/ASN1/Type/Tagged/ExplicitlyTaggedType.php index e908b8ce..722a179b 100644 --- a/src/ASN1/Type/Tagged/ExplicitlyTaggedType.php +++ b/src/ASN1/Type/Tagged/ExplicitlyTaggedType.php @@ -29,13 +29,13 @@ public function isConstructed(): bool public function explicit(): UnspecifiedType { - return $this->_element->asUnspecified(); + return $this->element->asUnspecified(); } protected function encodedAsDER(): string { // get the full encoding of the wrapped element - return $this->_element->toDER(); + return $this->element->toDER(); } protected static function decodeFromDER(Identifier $identifier, string $data, int &$offset): ElementBase diff --git a/src/ASN1/Type/Tagged/ImplicitlyTaggedType.php b/src/ASN1/Type/Tagged/ImplicitlyTaggedType.php index fc5f261d..359b6d1b 100644 --- a/src/ASN1/Type/Tagged/ImplicitlyTaggedType.php +++ b/src/ASN1/Type/Tagged/ImplicitlyTaggedType.php @@ -27,28 +27,28 @@ public static function create(int $tag, Element $element, int $class = Identifie public function isConstructed(): bool { // depends on the underlying type - return $this->_element->isConstructed(); + return $this->element->isConstructed(); } public function implicit(int $tag, int $class = Identifier::CLASS_UNIVERSAL): UnspecifiedType { - $this->_element->expectType($tag); - if ($this->_element->typeClass() !== $class) { + $this->element->expectType($tag); + if ($this->element->typeClass() !== $class) { throw new UnexpectedValueException( sprintf( 'Type class %s expected, got %s.', Identifier::classToName($class), - Identifier::classToName($this->_element->typeClass()) + Identifier::classToName($this->element->typeClass()) ) ); } - return $this->_element->asUnspecified(); + return $this->element->asUnspecified(); } protected function encodedAsDER(): string { // get only the content of the wrapped element. - return $this->_element->encodedAsDER(); + return $this->element->encodedAsDER(); } protected static function decodeFromDER(Identifier $identifier, string $data, int &$offset): ElementBase diff --git a/src/ASN1/Type/Tagged/TaggedTypeWrap.php b/src/ASN1/Type/Tagged/TaggedTypeWrap.php index 15f14630..afda029c 100644 --- a/src/ASN1/Type/Tagged/TaggedTypeWrap.php +++ b/src/ASN1/Type/Tagged/TaggedTypeWrap.php @@ -13,8 +13,8 @@ abstract class TaggedTypeWrap extends TaggedType { protected function __construct( - protected Element $_element, - protected int $_class, + protected readonly Element $element, + private readonly int $class, int $typeTag ) { parent::__construct($typeTag); @@ -22,6 +22,6 @@ protected function __construct( public function typeClass(): int { - return $this->_class; + return $this->class; } } diff --git a/src/ASN1/Type/UnspecifiedType.php b/src/ASN1/Type/UnspecifiedType.php index de43e5aa..1c0e9570 100644 --- a/src/ASN1/Type/UnspecifiedType.php +++ b/src/ASN1/Type/UnspecifiedType.php @@ -74,7 +74,7 @@ public static function fromElementBase(ElementBase $el): self if ($el instanceof self) { return $el; } - return new self($el->asElement()); + return self::create($el->asElement()); } /** @@ -83,7 +83,7 @@ public static function fromElementBase(ElementBase $el): self public function asTagged(): TaggedType { if (! $this->element instanceof TaggedType) { - throw new UnexpectedValueException('Tagged element expected, got ' . $this->_typeDescriptorString()); + throw new UnexpectedValueException('Tagged element expected, got ' . $this->typeDescriptorString()); } return $this->element; } @@ -94,7 +94,7 @@ public function asTagged(): TaggedType public function asApplication(): ApplicationType { if (! $this->element instanceof ApplicationType) { - throw new UnexpectedValueException('Application type expected, got ' . $this->_typeDescriptorString()); + throw new UnexpectedValueException('Application type expected, got ' . $this->typeDescriptorString()); } return $this->element; } @@ -105,7 +105,7 @@ public function asApplication(): ApplicationType public function asPrivate(): PrivateType { if (! $this->element instanceof PrivateType) { - throw new UnexpectedValueException('Private type expected, got ' . $this->_typeDescriptorString()); + throw new UnexpectedValueException('Private type expected, got ' . $this->typeDescriptorString()); } return $this->element; } @@ -116,7 +116,7 @@ public function asPrivate(): PrivateType public function asBoolean(): Boolean { if (! $this->element instanceof Boolean) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_BOOLEAN)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_BOOLEAN)); } return $this->element; } @@ -127,7 +127,7 @@ public function asBoolean(): Boolean public function asInteger(): Integer { if (! $this->element instanceof Integer) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_INTEGER)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_INTEGER)); } return $this->element; } @@ -138,7 +138,7 @@ public function asInteger(): Integer public function asBitString(): BitString { if (! $this->element instanceof BitString) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_BIT_STRING)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_BIT_STRING)); } return $this->element; } @@ -149,7 +149,7 @@ public function asBitString(): BitString public function asOctetString(): OctetString { if (! $this->element instanceof OctetString) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_OCTET_STRING)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_OCTET_STRING)); } return $this->element; } @@ -160,7 +160,7 @@ public function asOctetString(): OctetString public function asNull(): NullType { if (! $this->element instanceof NullType) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_NULL)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_NULL)); } return $this->element; } @@ -171,7 +171,7 @@ public function asNull(): NullType public function asObjectIdentifier(): ObjectIdentifier { if (! $this->element instanceof ObjectIdentifier) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_OBJECT_IDENTIFIER)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_OBJECT_IDENTIFIER)); } return $this->element; } @@ -182,7 +182,7 @@ public function asObjectIdentifier(): ObjectIdentifier public function asObjectDescriptor(): ObjectDescriptor { if (! $this->element instanceof ObjectDescriptor) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_OBJECT_DESCRIPTOR)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_OBJECT_DESCRIPTOR)); } return $this->element; } @@ -193,7 +193,7 @@ public function asObjectDescriptor(): ObjectDescriptor public function asReal(): Real { if (! $this->element instanceof Real) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_REAL)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_REAL)); } return $this->element; } @@ -204,7 +204,7 @@ public function asReal(): Real public function asEnumerated(): Enumerated { if (! $this->element instanceof Enumerated) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_ENUMERATED)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_ENUMERATED)); } return $this->element; } @@ -215,7 +215,7 @@ public function asEnumerated(): Enumerated public function asUTF8String(): UTF8String { if (! $this->element instanceof UTF8String) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_UTF8_STRING)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_UTF8_STRING)); } return $this->element; } @@ -226,7 +226,7 @@ public function asUTF8String(): UTF8String public function asRelativeOID(): RelativeOID { if (! $this->element instanceof RelativeOID) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_RELATIVE_OID)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_RELATIVE_OID)); } return $this->element; } @@ -237,7 +237,7 @@ public function asRelativeOID(): RelativeOID public function asSequence(): Sequence { if (! $this->element instanceof Sequence) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_SEQUENCE)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_SEQUENCE)); } return $this->element; } @@ -248,7 +248,7 @@ public function asSequence(): Sequence public function asSet(): Set { if (! $this->element instanceof Set) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_SET)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_SET)); } return $this->element; } @@ -259,7 +259,7 @@ public function asSet(): Set public function asNumericString(): NumericString { if (! $this->element instanceof NumericString) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_NUMERIC_STRING)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_NUMERIC_STRING)); } return $this->element; } @@ -270,7 +270,7 @@ public function asNumericString(): NumericString public function asPrintableString(): PrintableString { if (! $this->element instanceof PrintableString) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_PRINTABLE_STRING)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_PRINTABLE_STRING)); } return $this->element; } @@ -281,7 +281,7 @@ public function asPrintableString(): PrintableString public function asT61String(): T61String { if (! $this->element instanceof T61String) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_T61_STRING)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_T61_STRING)); } return $this->element; } @@ -292,7 +292,7 @@ public function asT61String(): T61String public function asVideotexString(): VideotexString { if (! $this->element instanceof VideotexString) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_VIDEOTEX_STRING)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_VIDEOTEX_STRING)); } return $this->element; } @@ -303,7 +303,7 @@ public function asVideotexString(): VideotexString public function asIA5String(): IA5String { if (! $this->element instanceof IA5String) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_IA5_STRING)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_IA5_STRING)); } return $this->element; } @@ -314,7 +314,7 @@ public function asIA5String(): IA5String public function asUTCTime(): UTCTime { if (! $this->element instanceof UTCTime) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_UTC_TIME)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_UTC_TIME)); } return $this->element; } @@ -325,7 +325,7 @@ public function asUTCTime(): UTCTime public function asGeneralizedTime(): GeneralizedTime { if (! $this->element instanceof GeneralizedTime) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_GENERALIZED_TIME)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_GENERALIZED_TIME)); } return $this->element; } @@ -336,7 +336,7 @@ public function asGeneralizedTime(): GeneralizedTime public function asGraphicString(): GraphicString { if (! $this->element instanceof GraphicString) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_GRAPHIC_STRING)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_GRAPHIC_STRING)); } return $this->element; } @@ -347,7 +347,7 @@ public function asGraphicString(): GraphicString public function asVisibleString(): VisibleString { if (! $this->element instanceof VisibleString) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_VISIBLE_STRING)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_VISIBLE_STRING)); } return $this->element; } @@ -358,7 +358,7 @@ public function asVisibleString(): VisibleString public function asGeneralString(): GeneralString { if (! $this->element instanceof GeneralString) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_GENERAL_STRING)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_GENERAL_STRING)); } return $this->element; } @@ -369,7 +369,7 @@ public function asGeneralString(): GeneralString public function asUniversalString(): UniversalString { if (! $this->element instanceof UniversalString) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_UNIVERSAL_STRING)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_UNIVERSAL_STRING)); } return $this->element; } @@ -380,7 +380,7 @@ public function asUniversalString(): UniversalString public function asCharacterString(): CharacterString { if (! $this->element instanceof CharacterString) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_CHARACTER_STRING)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_CHARACTER_STRING)); } return $this->element; } @@ -391,7 +391,7 @@ public function asCharacterString(): CharacterString public function asBMPString(): BMPString { if (! $this->element instanceof BMPString) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_BMP_STRING)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_BMP_STRING)); } return $this->element; } @@ -402,7 +402,7 @@ public function asBMPString(): BMPString public function asConstructedString(): ConstructedString { if (! $this->element instanceof ConstructedString) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_CONSTRUCTED_STRING)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_CONSTRUCTED_STRING)); } return $this->element; } @@ -413,7 +413,7 @@ public function asConstructedString(): ConstructedString public function asString(): StringType { if (! $this->element instanceof StringType) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_STRING)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_STRING)); } return $this->element; } @@ -424,7 +424,7 @@ public function asString(): StringType public function asTime(): TimeType { if (! $this->element instanceof TimeType) { - throw new UnexpectedValueException($this->_generateExceptionMessage(Element::TYPE_TIME)); + throw new UnexpectedValueException($this->generateExceptionMessage(Element::TYPE_TIME)); } return $this->element; } @@ -495,15 +495,15 @@ public function expectTagged(?int $tag = null): TaggedType * * @param int $tag Type tag of the expected element */ - private function _generateExceptionMessage(int $tag): string + private function generateExceptionMessage(int $tag): string { - return sprintf('%s expected, got %s.', Element::tagToName($tag), $this->_typeDescriptorString()); + return sprintf('%s expected, got %s.', Element::tagToName($tag), $this->typeDescriptorString()); } /** * Get textual description of the wrapped element for debugging purposes. */ - private function _typeDescriptorString(): string + private function typeDescriptorString(): string { $type_cls = $this->element->typeClass(); $tag = $this->element->tag(); diff --git a/src/ASN1/Util/BigInt.php b/src/ASN1/Util/BigInt.php index 5269cc7e..0e35ad11 100644 --- a/src/ASN1/Util/BigInt.php +++ b/src/ASN1/Util/BigInt.php @@ -65,7 +65,7 @@ public static function fromUnsignedOctets(string $octets): self if (mb_strlen($octets, '8bit') === 0) { throw new InvalidArgumentException('Empty octets.'); } - return new self(BigInteger::fromBytes($octets, false)); + return self::create(BigInteger::fromBytes($octets, false)); } /** @@ -77,7 +77,7 @@ public static function fromSignedOctets(string $octets): self throw new InvalidArgumentException('Empty octets.'); } - return new self(BigInteger::fromBytes($octets)); + return self::create(BigInteger::fromBytes($octets)); } /** diff --git a/src/ASN1/Util/Flags.php b/src/ASN1/Util/Flags.php index 29d5b8dd..3da1d3de 100644 --- a/src/ASN1/Util/Flags.php +++ b/src/ASN1/Util/Flags.php @@ -77,7 +77,7 @@ public static function fromBitString(BitString $bs, int $width): self if ($num_bits < $width) { $num = $num->shiftedLeft($width - $num_bits); } - return new self($num, $width); + return self::create($num, $width); } /** diff --git a/src/CryptoEncoding/PEM.php b/src/CryptoEncoding/PEM.php index ab4e5845..0001b88b 100644 --- a/src/CryptoEncoding/PEM.php +++ b/src/CryptoEncoding/PEM.php @@ -57,12 +57,12 @@ final class PEM implements Stringable '/ms'; /** - * @param string $_type Content type - * @param string $_data Payload + * @param string $type Content type + * @param string $data Payload */ private function __construct( - protected string $_type, - protected string $_data + private readonly string $type, + private readonly string $data ) { } @@ -89,7 +89,7 @@ public static function fromString(string $str): self if ($data === false) { throw new UnexpectedValueException('Failed to decode PEM data.'); } - return new self($match[1], $data); + return self::create($match[1], $data); } /** @@ -114,12 +114,12 @@ public static function fromFile(string $filename): self */ public function type(): string { - return $this->_type; + return $this->type; } public function data(): string { - return $this->_data; + return $this->data; } /** @@ -127,8 +127,8 @@ public function data(): string */ public function string(): string { - return "-----BEGIN {$this->_type}-----\n" . - trim(chunk_split(base64_encode($this->_data), 64, "\n")) . "\n" . - "-----END {$this->_type}-----"; + return "-----BEGIN {$this->type}-----\n" . + trim(chunk_split(base64_encode($this->data), 64, "\n")) . "\n" . + "-----END {$this->type}-----"; } } diff --git a/src/CryptoEncoding/PEMBundle.php b/src/CryptoEncoding/PEMBundle.php index c17f24c6..ae0cbe84 100644 --- a/src/CryptoEncoding/PEMBundle.php +++ b/src/CryptoEncoding/PEMBundle.php @@ -63,7 +63,7 @@ function ($match) { }, $matches ); - return new self(...$pems); + return self::create(...$pems); } /** diff --git a/src/CryptoTypes/AlgorithmIdentifier/AlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/AlgorithmIdentifier.php index 9e81dee6..bf8efd90 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/AlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/AlgorithmIdentifier.php @@ -98,7 +98,7 @@ abstract class AlgorithmIdentifier implements AlgorithmIdentifierType final public const OID_SHA512 = '2.16.840.1.101.3.4.2.3'; - public function __construct(protected string $oid) + protected function __construct(protected readonly string $oid) { } diff --git a/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/ECPublicKeyAlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/ECPublicKeyAlgorithmIdentifier.php index c569bfe8..64422c3e 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/ECPublicKeyAlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/ECPublicKeyAlgorithmIdentifier.php @@ -242,16 +242,16 @@ final class ECPublicKeyAlgorithmIdentifier extends SpecificAlgorithmIdentifier i ]; /** - * @param string $_namedCurve Curve identifier + * @param string $namedCurve Curve identifier */ - private function __construct(protected string $_namedCurve) + private function __construct(private readonly string $namedCurve) { parent::__construct(self::OID_EC_PUBLIC_KEY); } - public static function create(string $_namedCurve): self + public static function create(string $namedCurve): self { - return new self($_namedCurve); + return new self($namedCurve); } public function name(): string @@ -269,7 +269,7 @@ public static function fromASN1Params(?UnspecifiedType $params = null): Specific } $named_curve = $params->asObjectIdentifier() ->oid(); - return new self($named_curve); + return self::create($named_curve); } /** @@ -277,7 +277,7 @@ public static function fromASN1Params(?UnspecifiedType $params = null): Specific */ public function namedCurve(): string { - return $this->_namedCurve; + return $this->namedCurve; } /** @@ -285,6 +285,6 @@ public function namedCurve(): string */ protected function paramsASN1(): ?Element { - return ObjectIdentifier::create($this->_namedCurve); + return ObjectIdentifier::create($this->namedCurve); } } diff --git a/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/Ed25519AlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/Ed25519AlgorithmIdentifier.php index c838d540..1ac5f807 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/Ed25519AlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/Ed25519AlgorithmIdentifier.php @@ -37,7 +37,7 @@ public static function fromASN1Params(?UnspecifiedType $params = null): Specific if ($params !== null) { throw new UnexpectedValueException('Parameters must be absent.'); } - return new self(); + return self::create(); } public function name(): string diff --git a/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/Ed448AlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/Ed448AlgorithmIdentifier.php index 49fdc092..327fefbe 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/Ed448AlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/Ed448AlgorithmIdentifier.php @@ -37,7 +37,7 @@ public static function fromASN1Params(?UnspecifiedType $params = null): Specific if ($params !== null) { throw new UnexpectedValueException('Parameters must be absent.'); } - return new self(); + return self::create(); } public function name(): string diff --git a/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/RSAEncryptionAlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/RSAEncryptionAlgorithmIdentifier.php index 8164a955..3e87e889 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/RSAEncryptionAlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/RSAEncryptionAlgorithmIdentifier.php @@ -50,7 +50,7 @@ public static function fromASN1Params(?UnspecifiedType $params = null): Specific throw new UnexpectedValueException('No parameters.'); } $params->asNull(); - return new self(); + return self::create(); } /** diff --git a/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/X25519AlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/X25519AlgorithmIdentifier.php index 339a2d51..7f362d7a 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/X25519AlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/X25519AlgorithmIdentifier.php @@ -33,7 +33,7 @@ public static function fromASN1Params(?UnspecifiedType $params = null): Specific if ($params !== null) { throw new UnexpectedValueException('Parameters must be absent.'); } - return new self(); + return self::create(); } public function name(): string diff --git a/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/X448AlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/X448AlgorithmIdentifier.php index 819b9eab..d3fa9af6 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/X448AlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Asymmetric/X448AlgorithmIdentifier.php @@ -33,7 +33,7 @@ public static function fromASN1Params(?UnspecifiedType $params = null): Specific if ($params !== null) { throw new UnexpectedValueException('Parameters must be absent.'); } - return new self(); + return self::create(); } public function name(): string diff --git a/src/CryptoTypes/AlgorithmIdentifier/Cipher/AESCBCAlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Cipher/AESCBCAlgorithmIdentifier.php index 9a5b6c9c..f1e9f5ad 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Cipher/AESCBCAlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Cipher/AESCBCAlgorithmIdentifier.php @@ -34,9 +34,9 @@ public function ivSize(): int protected function paramsASN1(): OctetString { - if (! isset($this->_initializationVector)) { + if (! isset($this->initializationVector)) { throw new LogicException('IV not set.'); } - return OctetString::create($this->_initializationVector); + return OctetString::create($this->initializationVector); } } diff --git a/src/CryptoTypes/AlgorithmIdentifier/Cipher/CipherAlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Cipher/CipherAlgorithmIdentifier.php index cd0f3c8b..42cebdbd 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Cipher/CipherAlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Cipher/CipherAlgorithmIdentifier.php @@ -15,9 +15,9 @@ abstract class CipherAlgorithmIdentifier extends SpecificAlgorithmIdentifier { protected function __construct( string $oid, - protected string $_initializationVector + protected string $initializationVector ) { - $this->_checkIVSize($_initializationVector); + $this->_checkIVSize($initializationVector); parent::__construct($oid); } @@ -36,7 +36,7 @@ abstract public function ivSize(): int; */ public function initializationVector(): string { - return $this->_initializationVector; + return $this->initializationVector; } /** @@ -48,7 +48,7 @@ public function withInitializationVector(string $iv): self { $this->_checkIVSize($iv); $obj = clone $this; - $obj->_initializationVector = $iv; + $obj->initializationVector = $iv; return $obj; } diff --git a/src/CryptoTypes/AlgorithmIdentifier/Cipher/DESCBCAlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Cipher/DESCBCAlgorithmIdentifier.php index 82578b2e..efd7fbfe 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Cipher/DESCBCAlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Cipher/DESCBCAlgorithmIdentifier.php @@ -55,7 +55,7 @@ public static function fromASN1Params(?UnspecifiedType $params = null): Specific } $iv = $params->asOctetString() ->string(); - return new self($iv); + return self::create($iv); } public function blockSize(): int @@ -78,9 +78,9 @@ public function ivSize(): int */ protected function paramsASN1(): ?Element { - if (! isset($this->_initializationVector)) { + if (! isset($this->initializationVector)) { throw new LogicException('IV not set.'); } - return OctetString::create($this->_initializationVector); + return OctetString::create($this->initializationVector); } } diff --git a/src/CryptoTypes/AlgorithmIdentifier/Cipher/DESEDE3CBCAlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Cipher/DESEDE3CBCAlgorithmIdentifier.php index 11af459e..705475d7 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Cipher/DESEDE3CBCAlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Cipher/DESEDE3CBCAlgorithmIdentifier.php @@ -56,7 +56,7 @@ public static function fromASN1Params(?UnspecifiedType $params = null): Specific } $iv = $params->asOctetString() ->string(); - return new self($iv); + return self::create($iv); } public function blockSize(): int @@ -79,9 +79,9 @@ public function ivSize(): int */ protected function paramsASN1(): ?Element { - if (! isset($this->_initializationVector)) { + if (! isset($this->initializationVector)) { throw new LogicException('IV not set.'); } - return OctetString::create($this->_initializationVector); + return OctetString::create($this->initializationVector); } } diff --git a/src/CryptoTypes/AlgorithmIdentifier/Cipher/RC2CBCAlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Cipher/RC2CBCAlgorithmIdentifier.php index bb3b352b..d8d1043d 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Cipher/RC2CBCAlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Cipher/RC2CBCAlgorithmIdentifier.php @@ -92,11 +92,11 @@ final class RC2CBCAlgorithmIdentifier extends BlockCipherAlgorithmIdentifier ]; /** - * @param int $_effectiveKeyBits Number of effective key bits + * @param int $effectiveKeyBits Number of effective key bits * @param null|string $iv Initialization vector */ private function __construct( - protected int $_effectiveKeyBits, + private readonly int $effectiveKeyBits, ?string $iv ) { parent::__construct(self::OID_RC2_CBC, $iv); @@ -141,7 +141,7 @@ public static function fromASN1Params(?UnspecifiedType $params = null): Specific ->asOctetString() ->string(); } - return new self($key_bits, $iv); + return self::create($key_bits, $iv); } /** @@ -149,7 +149,7 @@ public static function fromASN1Params(?UnspecifiedType $params = null): Specific */ public function effectiveKeyBits(): int { - return $this->_effectiveKeyBits; + return $this->effectiveKeyBits; } public function blockSize(): int @@ -159,7 +159,7 @@ public function blockSize(): int public function keySize(): int { - return (int) round($this->_effectiveKeyBits / 8); + return (int) round($this->effectiveKeyBits / 8); } public function ivSize(): int @@ -172,15 +172,15 @@ public function ivSize(): int */ protected function paramsASN1(): ?Element { - if ($this->_effectiveKeyBits >= 256) { - $version = $this->_effectiveKeyBits; + if ($this->effectiveKeyBits >= 256) { + $version = $this->effectiveKeyBits; } else { - $version = self::EKB_TABLE[$this->_effectiveKeyBits]; + $version = self::EKB_TABLE[$this->effectiveKeyBits]; } - if (! isset($this->_initializationVector)) { + if (! isset($this->initializationVector)) { throw new LogicException('IV not set.'); } - return Sequence::create(Integer::create($version), OctetString::create($this->_initializationVector)); + return Sequence::create(Integer::create($version), OctetString::create($this->initializationVector)); } /** diff --git a/src/CryptoTypes/AlgorithmIdentifier/GenericAlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/GenericAlgorithmIdentifier.php index d6b6309e..2b63ae85 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/GenericAlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/GenericAlgorithmIdentifier.php @@ -14,18 +14,18 @@ final class GenericAlgorithmIdentifier extends AlgorithmIdentifier { /** * @param string $oid Algorithm OID - * @param null|UnspecifiedType $_params Parameters + * @param null|UnspecifiedType $params Parameters */ private function __construct( string $oid, - protected ?UnspecifiedType $_params = null + private readonly ?UnspecifiedType $params ) { parent::__construct($oid); } - public static function create(string $oid, ?UnspecifiedType $_params = null): self + public static function create(string $oid, ?UnspecifiedType $params = null): self { - return new self($oid, $_params); + return new self($oid, $params); } public function name(): string @@ -35,11 +35,11 @@ public function name(): string public function parameters(): ?UnspecifiedType { - return $this->_params; + return $this->params; } protected function paramsASN1(): ?Element { - return $this->_params?->asElement(); + return $this->params?->asElement(); } } diff --git a/src/CryptoTypes/AlgorithmIdentifier/Hash/HMACWithSHA1AlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Hash/HMACWithSHA1AlgorithmIdentifier.php index 6fbf79b5..4abf7901 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Hash/HMACWithSHA1AlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Hash/HMACWithSHA1AlgorithmIdentifier.php @@ -50,7 +50,7 @@ public static function fromASN1Params(?UnspecifiedType $params = null): Specific if (isset($params)) { throw new UnexpectedValueException('Parameters must be omitted.'); } - return new self(); + return self::create(); } protected function paramsASN1(): ?Element diff --git a/src/CryptoTypes/AlgorithmIdentifier/Hash/HMACWithSHA224AlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Hash/HMACWithSHA224AlgorithmIdentifier.php index 9d3536d2..85bf9426 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Hash/HMACWithSHA224AlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Hash/HMACWithSHA224AlgorithmIdentifier.php @@ -4,6 +4,7 @@ namespace SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Hash; +use SpomkyLabs\Pki\ASN1\Element; use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType; /** @@ -13,14 +14,14 @@ */ final class HMACWithSHA224AlgorithmIdentifier extends RFC4231HMACAlgorithmIdentifier { - private function __construct() + private function __construct(?Element $params) { - parent::__construct(self::OID_HMAC_WITH_SHA224); + parent::__construct(self::OID_HMAC_WITH_SHA224, $params); } - public static function create(): self + public static function create(?Element $params = null): self { - return new self(); + return new self($params); } public static function fromASN1Params(?UnspecifiedType $params = null): self @@ -29,11 +30,7 @@ public static function fromASN1Params(?UnspecifiedType $params = null): self * RFC 4231 states that the "parameter" component SHOULD be present * but have type NULL. */ - $obj = new self(); - if ($params !== null) { - $obj->params = $params->asNull(); - } - return $obj; + return self::create($params?->asNull()); } public function name(): string diff --git a/src/CryptoTypes/AlgorithmIdentifier/Hash/HMACWithSHA256AlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Hash/HMACWithSHA256AlgorithmIdentifier.php index ba3dab22..bd794d43 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Hash/HMACWithSHA256AlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Hash/HMACWithSHA256AlgorithmIdentifier.php @@ -4,6 +4,7 @@ namespace SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Hash; +use SpomkyLabs\Pki\ASN1\Element; use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType; /** @@ -13,14 +14,14 @@ */ final class HMACWithSHA256AlgorithmIdentifier extends RFC4231HMACAlgorithmIdentifier { - private function __construct() + private function __construct(?Element $params) { - parent::__construct(self::OID_HMAC_WITH_SHA256); + parent::__construct(self::OID_HMAC_WITH_SHA256, $params); } - public static function create(): self + public static function create(?Element $params = null): self { - return new self(); + return new self($params); } public static function fromASN1Params(?UnspecifiedType $params = null): self @@ -29,11 +30,7 @@ public static function fromASN1Params(?UnspecifiedType $params = null): self * RFC 4231 states that the "parameter" component SHOULD be present * but have type NULL. */ - $obj = new self(); - if ($params !== null) { - $obj->params = $params->asNull(); - } - return $obj; + return self::create($params?->asNull()); } public function name(): string diff --git a/src/CryptoTypes/AlgorithmIdentifier/Hash/HMACWithSHA384AlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Hash/HMACWithSHA384AlgorithmIdentifier.php index 7ad6e4f7..7fe1dacb 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Hash/HMACWithSHA384AlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Hash/HMACWithSHA384AlgorithmIdentifier.php @@ -4,6 +4,7 @@ namespace SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Hash; +use SpomkyLabs\Pki\ASN1\Element; use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType; /** @@ -13,14 +14,14 @@ */ final class HMACWithSHA384AlgorithmIdentifier extends RFC4231HMACAlgorithmIdentifier { - private function __construct() + private function __construct(?Element $params) { - parent::__construct(self::OID_HMAC_WITH_SHA384); + parent::__construct(self::OID_HMAC_WITH_SHA384, $params); } - public static function create(): self + public static function create(?Element $params = null): self { - return new self(); + return new self($params); } public static function fromASN1Params(?UnspecifiedType $params = null): self @@ -29,11 +30,7 @@ public static function fromASN1Params(?UnspecifiedType $params = null): self * RFC 4231 states that the "parameter" component SHOULD be present * but have type NULL. */ - $obj = new self(); - if ($params !== null) { - $obj->params = $params->asNull(); - } - return $obj; + return new self($params?->asNull()); } public function name(): string diff --git a/src/CryptoTypes/AlgorithmIdentifier/Hash/HMACWithSHA512AlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Hash/HMACWithSHA512AlgorithmIdentifier.php index 40e623e9..5d5ecdd6 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Hash/HMACWithSHA512AlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Hash/HMACWithSHA512AlgorithmIdentifier.php @@ -4,6 +4,7 @@ namespace SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Hash; +use SpomkyLabs\Pki\ASN1\Element; use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType; /** @@ -13,14 +14,14 @@ */ final class HMACWithSHA512AlgorithmIdentifier extends RFC4231HMACAlgorithmIdentifier { - private function __construct() + private function __construct(?Element $params) { - parent::__construct(self::OID_HMAC_WITH_SHA512); + parent::__construct(self::OID_HMAC_WITH_SHA512, $params); } - public static function create(): self + public static function create(?Element $params = null): self { - return new self(); + return new self($params); } public static function fromASN1Params(?UnspecifiedType $params = null): self @@ -29,11 +30,7 @@ public static function fromASN1Params(?UnspecifiedType $params = null): self * RFC 4231 states that the "parameter" component SHOULD be present * but have type NULL. */ - $obj = new self(); - if ($params !== null) { - $obj->params = $params->asNull(); - } - return $obj; + return self::create($params?->asNull()); } public function name(): string diff --git a/src/CryptoTypes/AlgorithmIdentifier/Hash/MD5AlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Hash/MD5AlgorithmIdentifier.php index b29f8579..94345cf5 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Hash/MD5AlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Hash/MD5AlgorithmIdentifier.php @@ -36,12 +36,17 @@ final class MD5AlgorithmIdentifier extends SpecificAlgorithmIdentifier implement /** * Parameters. */ - protected ?NullType $_params; + private ?NullType $params; - public function __construct() + private function __construct() { parent::__construct(self::OID_MD5); - $this->_params = NullType::create(); + $this->params = NullType::create(); + } + + public static function create(): self + { + return new self(); } public function name(): string @@ -49,15 +54,12 @@ public function name(): string return 'md5'; } - /** - * @return self - */ - public static function fromASN1Params(?UnspecifiedType $params = null): SpecificAlgorithmIdentifier + public static function fromASN1Params(?UnspecifiedType $params = null): static { - $obj = new static(); + $obj = static::create(); // if parameters field is present, it must be null type if (isset($params)) { - $obj->_params = $params->asNull(); + $obj->params = $params->asNull(); } return $obj; } @@ -67,6 +69,6 @@ public static function fromASN1Params(?UnspecifiedType $params = null): Specific */ protected function paramsASN1(): ?Element { - return $this->_params; + return $this->params; } } diff --git a/src/CryptoTypes/AlgorithmIdentifier/Hash/RFC4231HMACAlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Hash/RFC4231HMACAlgorithmIdentifier.php index 59c55791..b341c6ea 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Hash/RFC4231HMACAlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Hash/RFC4231HMACAlgorithmIdentifier.php @@ -18,9 +18,14 @@ abstract class RFC4231HMACAlgorithmIdentifier extends SpecificAlgorithmIdentifier implements HashAlgorithmIdentifier, PRFAlgorithmIdentifier { /** - * Parameters stored for re-encoding. + * @param Element|null $params Parameters stored for re-encoding. */ - protected ?NullType $params = null; + protected function __construct( + string $oid, + protected ?Element $params + ) { + parent::__construct($oid); + } /** * @return null|NullType diff --git a/src/CryptoTypes/AlgorithmIdentifier/Hash/SHA1AlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Hash/SHA1AlgorithmIdentifier.php index 9baad775..2eec340f 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Hash/SHA1AlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Hash/SHA1AlgorithmIdentifier.php @@ -32,12 +32,17 @@ final class SHA1AlgorithmIdentifier extends SpecificAlgorithmIdentifier implemen /** * Parameters. */ - protected ?NullType $_params; + private ?NullType $params; - public function __construct() + private function __construct() { parent::__construct(self::OID_SHA1); - $this->_params = null; + $this->params = null; + } + + public static function create(): self + { + return new self(); } public function name(): string @@ -45,15 +50,12 @@ public function name(): string return 'sha1'; } - /** - * @return self - */ - public static function fromASN1Params(?UnspecifiedType $params = null): SpecificAlgorithmIdentifier + public static function fromASN1Params(?UnspecifiedType $params = null): static { - $obj = new static(); + $obj = static::create(); // if parameters field is present, it must be null type if (isset($params)) { - $obj->_params = $params->asNull(); + $obj->params = $params->asNull(); } return $obj; } @@ -63,6 +65,6 @@ public static function fromASN1Params(?UnspecifiedType $params = null): Specific */ protected function paramsASN1(): ?Element { - return $this->_params; + return $this->params; } } diff --git a/src/CryptoTypes/AlgorithmIdentifier/Signature/ECDSAWithSHA1AlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Signature/ECDSAWithSHA1AlgorithmIdentifier.php index ce048cd2..fe462024 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Signature/ECDSAWithSHA1AlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Signature/ECDSAWithSHA1AlgorithmIdentifier.php @@ -34,6 +34,6 @@ public static function fromASN1Params(?UnspecifiedType $params = null): self if ($params !== null) { throw new UnexpectedValueException('Parameters must be omitted.'); } - return new self(); + return self::create(); } } diff --git a/src/CryptoTypes/AlgorithmIdentifier/Signature/ECDSAWithSHA224AlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Signature/ECDSAWithSHA224AlgorithmIdentifier.php index 2a0810e4..d5ca3ecb 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Signature/ECDSAWithSHA224AlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Signature/ECDSAWithSHA224AlgorithmIdentifier.php @@ -34,6 +34,6 @@ public static function fromASN1Params(?UnspecifiedType $params = null): self if ($params !== null) { throw new UnexpectedValueException('Parameters must be omitted.'); } - return new self(); + return self::create(); } } diff --git a/src/CryptoTypes/AlgorithmIdentifier/Signature/ECDSAWithSHA256AlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Signature/ECDSAWithSHA256AlgorithmIdentifier.php index 90923490..6840c287 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Signature/ECDSAWithSHA256AlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Signature/ECDSAWithSHA256AlgorithmIdentifier.php @@ -34,6 +34,6 @@ public static function fromASN1Params(?UnspecifiedType $params = null): self if ($params !== null) { throw new UnexpectedValueException('Parameters must be omitted.'); } - return new self(); + return self::create(); } } diff --git a/src/CryptoTypes/AlgorithmIdentifier/Signature/ECDSAWithSHA384AlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Signature/ECDSAWithSHA384AlgorithmIdentifier.php index 352ee013..b7dea16a 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Signature/ECDSAWithSHA384AlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Signature/ECDSAWithSHA384AlgorithmIdentifier.php @@ -34,6 +34,6 @@ public static function fromASN1Params(?UnspecifiedType $params = null): self if ($params !== null) { throw new UnexpectedValueException('Parameters must be omitted.'); } - return new self(); + return self::create(); } } diff --git a/src/CryptoTypes/AlgorithmIdentifier/Signature/ECDSAWithSHA512AlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Signature/ECDSAWithSHA512AlgorithmIdentifier.php index 5148de02..4a2aba8e 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Signature/ECDSAWithSHA512AlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Signature/ECDSAWithSHA512AlgorithmIdentifier.php @@ -29,7 +29,7 @@ public static function fromASN1Params(?UnspecifiedType $params = null): self if ($params !== null) { throw new UnexpectedValueException('Parameters must be omitted.'); } - return new self(); + return self::create(); } public function name(): string diff --git a/src/CryptoTypes/AlgorithmIdentifier/Signature/MD2WithRSAEncryptionAlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Signature/MD2WithRSAEncryptionAlgorithmIdentifier.php index 2a82dccf..c9f216ec 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Signature/MD2WithRSAEncryptionAlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Signature/MD2WithRSAEncryptionAlgorithmIdentifier.php @@ -29,8 +29,7 @@ public static function fromASN1Params(?UnspecifiedType $params = null): self if (! isset($params)) { throw new UnexpectedValueException('No parameters.'); } - $params->asNull(); - return new self(); + return self::create(); } public function name(): string diff --git a/src/CryptoTypes/AlgorithmIdentifier/Signature/MD4WithRSAEncryptionAlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Signature/MD4WithRSAEncryptionAlgorithmIdentifier.php index d5927e29..fe6079eb 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Signature/MD4WithRSAEncryptionAlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Signature/MD4WithRSAEncryptionAlgorithmIdentifier.php @@ -29,8 +29,7 @@ public static function fromASN1Params(?UnspecifiedType $params = null): self if (! isset($params)) { throw new UnexpectedValueException('No parameters.'); } - $params->asNull(); - return new self(); + return self::create(); } public function name(): string diff --git a/src/CryptoTypes/AlgorithmIdentifier/Signature/MD5WithRSAEncryptionAlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Signature/MD5WithRSAEncryptionAlgorithmIdentifier.php index 66eaec3c..593d3ccf 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Signature/MD5WithRSAEncryptionAlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Signature/MD5WithRSAEncryptionAlgorithmIdentifier.php @@ -29,8 +29,7 @@ public static function fromASN1Params(?UnspecifiedType $params = null): self if (! isset($params)) { throw new UnexpectedValueException('No parameters.'); } - $params->asNull(); - return new self(); + return self::create(); } public function name(): string diff --git a/src/CryptoTypes/AlgorithmIdentifier/Signature/RFC4055RSASignatureAlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Signature/RFC4055RSASignatureAlgorithmIdentifier.php index 655690eb..e9ae13bd 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Signature/RFC4055RSASignatureAlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Signature/RFC4055RSASignatureAlgorithmIdentifier.php @@ -5,7 +5,6 @@ namespace SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Signature; use SpomkyLabs\Pki\ASN1\Element; -use SpomkyLabs\Pki\ASN1\Type\Primitive\NullType; /* From RFC 4055 - 5. PKCS #1 Version 1.5 Signature Algorithm @@ -22,12 +21,11 @@ */ abstract class RFC4055RSASignatureAlgorithmIdentifier extends RSASignatureAlgorithmIdentifier { - protected null|Element $params; - - protected function __construct(string $oid) - { + protected function __construct( + string $oid, + protected null|Element $params + ) { parent::__construct($oid); - $this->params = NullType::create(); } protected function paramsASN1(): ?Element diff --git a/src/CryptoTypes/AlgorithmIdentifier/Signature/SHA1WithRSAEncryptionAlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Signature/SHA1WithRSAEncryptionAlgorithmIdentifier.php index b6ee396a..22a7b631 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Signature/SHA1WithRSAEncryptionAlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Signature/SHA1WithRSAEncryptionAlgorithmIdentifier.php @@ -30,7 +30,7 @@ public static function fromASN1Params(?UnspecifiedType $params = null): self throw new UnexpectedValueException('No parameters.'); } $params->asNull(); - return new self(); + return self::create(); } public function name(): string diff --git a/src/CryptoTypes/AlgorithmIdentifier/Signature/SHA224WithRSAEncryptionAlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Signature/SHA224WithRSAEncryptionAlgorithmIdentifier.php index 6242a3aa..15fa6507 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Signature/SHA224WithRSAEncryptionAlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Signature/SHA224WithRSAEncryptionAlgorithmIdentifier.php @@ -4,6 +4,7 @@ namespace SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Signature; +use SpomkyLabs\Pki\ASN1\Element; use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType; /** @@ -13,24 +14,20 @@ */ final class SHA224WithRSAEncryptionAlgorithmIdentifier extends RFC4055RSASignatureAlgorithmIdentifier { - private function __construct() + private function __construct(null|Element $params) { - parent::__construct(self::OID_SHA224_WITH_RSA_ENCRYPTION); + parent::__construct(self::OID_SHA224_WITH_RSA_ENCRYPTION, $params); } - public static function create(): self + public static function create(null|Element $params = null): self { - return new self(); + return new self($params); } public static function fromASN1Params(?UnspecifiedType $params = null): self { - $obj = new self(); // store parameters so re-encoding doesn't change - if (isset($params)) { - $obj->params = $params->asElement(); - } - return $obj; + return self::create($params?->asElement()); } public function name(): string diff --git a/src/CryptoTypes/AlgorithmIdentifier/Signature/SHA256WithRSAEncryptionAlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Signature/SHA256WithRSAEncryptionAlgorithmIdentifier.php index 7ccaf7cf..be749d4c 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Signature/SHA256WithRSAEncryptionAlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Signature/SHA256WithRSAEncryptionAlgorithmIdentifier.php @@ -4,6 +4,7 @@ namespace SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Signature; +use SpomkyLabs\Pki\ASN1\Element; use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType; /** @@ -13,24 +14,20 @@ */ final class SHA256WithRSAEncryptionAlgorithmIdentifier extends RFC4055RSASignatureAlgorithmIdentifier { - private function __construct() + private function __construct(null|Element $params) { - parent::__construct(self::OID_SHA256_WITH_RSA_ENCRYPTION); + parent::__construct(self::OID_SHA256_WITH_RSA_ENCRYPTION, $params); } - public static function create(): self + public static function create(null|Element $params = null): self { - return new self(); + return new self($params); } public static function fromASN1Params(?UnspecifiedType $params = null): self { - $obj = new self(); // store parameters so re-encoding doesn't change - if (isset($params)) { - $obj->params = $params->asElement(); - } - return $obj; + return self::create($params?->asElement()); } public function name(): string diff --git a/src/CryptoTypes/AlgorithmIdentifier/Signature/SHA384WithRSAEncryptionAlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Signature/SHA384WithRSAEncryptionAlgorithmIdentifier.php index 0d5ce28d..76407874 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Signature/SHA384WithRSAEncryptionAlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Signature/SHA384WithRSAEncryptionAlgorithmIdentifier.php @@ -4,6 +4,7 @@ namespace SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Signature; +use SpomkyLabs\Pki\ASN1\Element; use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType; /** @@ -13,24 +14,20 @@ */ final class SHA384WithRSAEncryptionAlgorithmIdentifier extends RFC4055RSASignatureAlgorithmIdentifier { - protected function __construct() + protected function __construct(null|Element $params) { - parent::__construct(self::OID_SHA384_WITH_RSA_ENCRYPTION); + parent::__construct(self::OID_SHA384_WITH_RSA_ENCRYPTION, $params); } - public static function create(): self + public static function create(null|Element $params = null): self { - return new self(); + return new self($params); } public static function fromASN1Params(?UnspecifiedType $params = null): self { - $obj = new self(); // store parameters so re-encoding doesn't change - if (isset($params)) { - $obj->params = $params->asElement(); - } - return $obj; + return self::create($params?->asElement()); } public function name(): string diff --git a/src/CryptoTypes/AlgorithmIdentifier/Signature/SHA512WithRSAEncryptionAlgorithmIdentifier.php b/src/CryptoTypes/AlgorithmIdentifier/Signature/SHA512WithRSAEncryptionAlgorithmIdentifier.php index 9b18b8c5..58a7f3fb 100644 --- a/src/CryptoTypes/AlgorithmIdentifier/Signature/SHA512WithRSAEncryptionAlgorithmIdentifier.php +++ b/src/CryptoTypes/AlgorithmIdentifier/Signature/SHA512WithRSAEncryptionAlgorithmIdentifier.php @@ -4,6 +4,7 @@ namespace SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Signature; +use SpomkyLabs\Pki\ASN1\Element; use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType; /** @@ -13,24 +14,20 @@ */ final class SHA512WithRSAEncryptionAlgorithmIdentifier extends RFC4055RSASignatureAlgorithmIdentifier { - private function __construct() + private function __construct(null|Element $params) { - parent::__construct(self::OID_SHA512_WITH_RSA_ENCRYPTION); + parent::__construct(self::OID_SHA512_WITH_RSA_ENCRYPTION, $params); } - public static function create(): self + public static function create(null|Element $params = null): self { - return new self(); + return new self($params); } public static function fromASN1Params(?UnspecifiedType $params = null): self { - $obj = new self(); // store parameters so re-encoding doesn't change - if (isset($params)) { - $obj->params = $params->asElement(); - } - return $obj; + return self::create($params?->asElement()); } public function name(): string diff --git a/src/CryptoTypes/Asymmetric/EC/ECPrivateKey.php b/src/CryptoTypes/Asymmetric/EC/ECPrivateKey.php index 60296d8d..cb9a8f02 100644 --- a/src/CryptoTypes/Asymmetric/EC/ECPrivateKey.php +++ b/src/CryptoTypes/Asymmetric/EC/ECPrivateKey.php @@ -27,17 +27,25 @@ final class ECPrivateKey extends PrivateKey { /** - * @param string $_privateKey Private key - * @param null|string $_namedCurve OID of the named curve - * @param null|string $_publicKey ECPoint value + * @param string $privateKey Private key + * @param null|string $namedCurve OID of the named curve + * @param null|string $publicKey ECPoint value */ - public function __construct( - protected string $_privateKey, - protected ?string $_namedCurve = null, - protected ?string $_publicKey = null + private function __construct( + private readonly string $privateKey, + private ?string $namedCurve, + private readonly ?string $publicKey ) { } + public static function create( + string $privateKey, + ?string $namedCurve = null, + ?string $publicKey = null + ): self { + return new self($privateKey, $namedCurve, $publicKey); + } + /** * Initialize from ASN.1. */ @@ -66,7 +74,7 @@ public static function fromASN1(Sequence $seq): self ->asBitString() ->string(); } - return new self($private_key, $named_curve, $public_key); + return self::create($private_key, $named_curve, $public_key); } /** @@ -96,7 +104,7 @@ public static function fromPEM(PEM $pem): self */ public function privateKeyOctets(): string { - return $this->_privateKey; + return $this->privateKey; } /** @@ -104,7 +112,7 @@ public function privateKeyOctets(): string */ public function hasNamedCurve(): bool { - return isset($this->_namedCurve); + return isset($this->namedCurve); } /** @@ -115,7 +123,7 @@ public function namedCurve(): string if (! $this->hasNamedCurve()) { throw new LogicException('namedCurve not set.'); } - return $this->_namedCurve; + return $this->namedCurve; } /** @@ -126,7 +134,7 @@ public function namedCurve(): string public function withNamedCurve(?string $named_curve): self { $obj = clone $this; - $obj->_namedCurve = $named_curve; + $obj->namedCurve = $named_curve; return $obj; } @@ -140,7 +148,7 @@ public function algorithmIdentifier(): AlgorithmIdentifierType */ public function hasPublicKey(): bool { - return isset($this->_publicKey); + return isset($this->publicKey); } /** @@ -151,7 +159,7 @@ public function publicKey(): PublicKey if (! $this->hasPublicKey()) { throw new LogicException('publicKey not set.'); } - return new ECPublicKey($this->_publicKey, $this->namedCurve()); + return ECPublicKey::create($this->publicKey, $this->namedCurve()); } /** @@ -159,12 +167,12 @@ public function publicKey(): PublicKey */ public function toASN1(): Sequence { - $elements = [Integer::create(1), OctetString::create($this->_privateKey)]; - if (isset($this->_namedCurve)) { - $elements[] = ExplicitlyTaggedType::create(0, ObjectIdentifier::create($this->_namedCurve)); + $elements = [Integer::create(1), OctetString::create($this->privateKey)]; + if (isset($this->namedCurve)) { + $elements[] = ExplicitlyTaggedType::create(0, ObjectIdentifier::create($this->namedCurve)); } - if (isset($this->_publicKey)) { - $elements[] = ExplicitlyTaggedType::create(1, BitString::create($this->_publicKey)); + if (isset($this->publicKey)) { + $elements[] = ExplicitlyTaggedType::create(1, BitString::create($this->publicKey)); } return Sequence::create(...$elements); } diff --git a/src/CryptoTypes/Asymmetric/EC/ECPublicKey.php b/src/CryptoTypes/Asymmetric/EC/ECPublicKey.php index 9a0a3524..00c9e52f 100644 --- a/src/CryptoTypes/Asymmetric/EC/ECPublicKey.php +++ b/src/CryptoTypes/Asymmetric/EC/ECPublicKey.php @@ -32,22 +32,27 @@ final class ECPublicKey extends PublicKey /** * Elliptic curve public key. */ - protected string $_ecPoint; + private readonly string $ecPoint; /** - * @param string $ec_point ECPoint - * @param null|string $_namedCurve Named curve OID + * @param string $ecPoint ECPoint + * @param null|string $namedCurve Named curve OID */ - public function __construct( - string $ec_point, - protected ?string $_namedCurve = null + private function __construct( + string $ecPoint, + private readonly ?string $namedCurve ) { // first octet must be 0x04 for uncompressed form, and 0x02 or 0x03 // for compressed form. - if (($ec_point === '') || ! in_array(ord($ec_point[0]), [2, 3, 4], true)) { + if (($ecPoint === '') || ! in_array(ord($ecPoint[0]), [2, 3, 4], true)) { throw new InvalidArgumentException('Invalid ECPoint.'); } - $this->_ecPoint = $ec_point; + $this->ecPoint = $ecPoint; + } + + public static function create(string $ecPoint, ?string $namedCurve = null): self + { + return new self($ecPoint, $namedCurve); } /** @@ -75,7 +80,7 @@ public static function fromCoordinates( $x_os = ECConversion::integerToOctetString(Integer::create($x), $mlen)->string(); $y_os = ECConversion::integerToOctetString(Integer::create($y), $mlen)->string(); $ec_point = "\x4{$x_os}{$y_os}"; - return new self($ec_point, $named_curve); + return self::create($ec_point, $named_curve); } /** @@ -93,7 +98,7 @@ public static function fromPEM(PEM $pem): self throw new UnexpectedValueException('Not an elliptic curve key.'); } // ECPoint is directly mapped into public key data - return new self($pki->publicKeyData()->string(), $algo->namedCurve()); + return self::create($pki->publicKeyData()->string(), $algo->namedCurve()); } /** @@ -101,7 +106,7 @@ public static function fromPEM(PEM $pem): self */ public function ECPoint(): string { - return $this->_ecPoint; + return $this->ecPoint; } /** @@ -124,7 +129,7 @@ public function curvePointOctets(): array if ($this->isCompressed()) { throw new RuntimeException('EC point compression not supported.'); } - $str = mb_substr($this->_ecPoint, 1, null, '8bit'); + $str = mb_substr($this->ecPoint, 1, null, '8bit'); $length = (int) floor(mb_strlen($str, '8bit') / 2); if ($length < 1) { throw new RuntimeException('Invalid EC point.'); @@ -138,7 +143,7 @@ public function curvePointOctets(): array */ public function isCompressed(): bool { - $c = ord($this->_ecPoint[0]); + $c = ord($this->ecPoint[0]); return $c !== 4; } @@ -147,7 +152,7 @@ public function isCompressed(): bool */ public function hasNamedCurve(): bool { - return isset($this->_namedCurve); + return isset($this->namedCurve); } /** @@ -158,7 +163,7 @@ public function namedCurve(): string if (! $this->hasNamedCurve()) { throw new LogicException('namedCurve not set.'); } - return $this->_namedCurve; + return $this->namedCurve; } public function algorithmIdentifier(): AlgorithmIdentifierType @@ -171,7 +176,7 @@ public function algorithmIdentifier(): AlgorithmIdentifierType */ public function toASN1(): OctetString { - return OctetString::create($this->_ecPoint); + return OctetString::create($this->ecPoint); } public function toDER(): string @@ -186,7 +191,7 @@ public function toDER(): string public function subjectPublicKey(): BitString { // ECPoint is directly mapped to subjectPublicKey - return BitString::create($this->_ecPoint); + return BitString::create($this->ecPoint); } /** diff --git a/src/CryptoTypes/Asymmetric/OneAsymmetricKey.php b/src/CryptoTypes/Asymmetric/OneAsymmetricKey.php index 8dfd9d42..ab976536 100644 --- a/src/CryptoTypes/Asymmetric/OneAsymmetricKey.php +++ b/src/CryptoTypes/Asymmetric/OneAsymmetricKey.php @@ -55,28 +55,28 @@ class OneAsymmetricKey private int $version; /** - * @param AlgorithmIdentifierType $_algo Algorithm - * @param string $_privateKeyData Private key data - * @param null|OneAsymmetricKeyAttributes $_attributes Optional attributes - * @param null|BitString $_publicKeyData Optional public key + * @param AlgorithmIdentifierType $algo Algorithm + * @param string $privateKeyData Private key data + * @param null|OneAsymmetricKeyAttributes $attributes Optional attributes + * @param null|BitString $publicKeyData Optional public key */ protected function __construct( - protected AlgorithmIdentifierType $_algo, - protected string $_privateKeyData, - protected ?OneAsymmetricKeyAttributes $_attributes = null, - protected ?BitString $_publicKeyData = null, + protected AlgorithmIdentifierType $algo, + protected string $privateKeyData, + protected ?OneAsymmetricKeyAttributes $attributes = null, + protected ?BitString $publicKeyData = null, ?int $version = null ) { $this->version = $version ?? self::VERSION_2; } public static function create( - AlgorithmIdentifierType $_algo, - string $_privateKeyData, - ?OneAsymmetricKeyAttributes $_attributes = null, - ?BitString $_publicKeyData = null + AlgorithmIdentifierType $algo, + string $privateKeyData, + ?OneAsymmetricKeyAttributes $attributes = null, + ?BitString $publicKeyData = null ): self { - return new self($_algo, $_privateKeyData, $_attributes, $_publicKeyData); + return new self($algo, $privateKeyData, $attributes, $publicKeyData); } /** @@ -163,7 +163,7 @@ public function version(): int */ public function algorithmIdentifier(): AlgorithmIdentifierType { - return $this->_algo; + return $this->algo; } /** @@ -171,7 +171,7 @@ public function algorithmIdentifier(): AlgorithmIdentifierType */ public function privateKeyData(): string { - return $this->_privateKeyData; + return $this->privateKeyData; } /** @@ -183,10 +183,10 @@ public function privateKey(): PrivateKey switch ($algo->oid()) { // RSA case AlgorithmIdentifier::OID_RSA_ENCRYPTION: - return RSAPrivateKey::fromDER($this->_privateKeyData); + return RSAPrivateKey::fromDER($this->privateKeyData); // elliptic curve case AlgorithmIdentifier::OID_EC_PUBLIC_KEY: - $pk = ECPrivateKey::fromDER($this->_privateKeyData); + $pk = ECPrivateKey::fromDER($this->privateKeyData); // NOTE: OpenSSL strips named curve from ECPrivateKey structure // when serializing into PrivateKeyInfo. However, RFC 5915 dictates // that parameters (NamedCurve) must always be included. @@ -200,31 +200,31 @@ public function privateKey(): PrivateKey return $pk; // Ed25519 case AlgorithmIdentifier::OID_ED25519: - $pubkey = $this->_publicKeyData?->string(); + $pubkey = $this->publicKeyData?->string(); // RFC 8410 defines `CurvePrivateKey ::= OCTET STRING` that // is encoded into private key data. So Ed25519 private key // is doubly wrapped into octet string encodings. - return Ed25519PrivateKey::fromOctetString(OctetString::fromDER($this->_privateKeyData), $pubkey) + return Ed25519PrivateKey::fromOctetString(OctetString::fromDER($this->privateKeyData), $pubkey) ->withVersion($this->version) - ->withAttributes($this->_attributes); + ->withAttributes($this->attributes); // X25519 case AlgorithmIdentifier::OID_X25519: - $pubkey = $this->_publicKeyData?->string(); - return X25519PrivateKey::fromOctetString(OctetString::fromDER($this->_privateKeyData), $pubkey) + $pubkey = $this->publicKeyData?->string(); + return X25519PrivateKey::fromOctetString(OctetString::fromDER($this->privateKeyData), $pubkey) ->withVersion($this->version) - ->withAttributes($this->_attributes); + ->withAttributes($this->attributes); // Ed448 case AlgorithmIdentifier::OID_ED448: - $pubkey = $this->_publicKeyData?->string(); - return Ed448PrivateKey::fromOctetString(OctetString::fromDER($this->_privateKeyData), $pubkey) + $pubkey = $this->publicKeyData?->string(); + return Ed448PrivateKey::fromOctetString(OctetString::fromDER($this->privateKeyData), $pubkey) ->withVersion($this->version) - ->withAttributes($this->_attributes); + ->withAttributes($this->attributes); // X448 case AlgorithmIdentifier::OID_X448: - $pubkey = $this->_publicKeyData?->string(); - return X448PrivateKey::fromOctetString(OctetString::fromDER($this->_privateKeyData), $pubkey) + $pubkey = $this->publicKeyData?->string(); + return X448PrivateKey::fromOctetString(OctetString::fromDER($this->privateKeyData), $pubkey) ->withVersion($this->version) - ->withAttributes($this->_attributes); + ->withAttributes($this->attributes); } throw new RuntimeException('Private key ' . $algo->name() . ' not supported.'); } @@ -236,7 +236,7 @@ public function publicKeyInfo(): PublicKeyInfo { // if public key is explicitly defined if ($this->hasPublicKeyData()) { - return new PublicKeyInfo($this->_algo, $this->_publicKeyData); + return PublicKeyInfo::create($this->algo, $this->publicKeyData); } // else derive from private key return $this->privateKey() @@ -249,7 +249,7 @@ public function publicKeyInfo(): PublicKeyInfo */ public function hasAttributes(): bool { - return isset($this->_attributes); + return isset($this->attributes); } public function attributes(): OneAsymmetricKeyAttributes @@ -257,7 +257,7 @@ public function attributes(): OneAsymmetricKeyAttributes if (! $this->hasAttributes()) { throw new LogicException('Attributes not set.'); } - return $this->_attributes; + return $this->attributes; } /** @@ -265,7 +265,7 @@ public function attributes(): OneAsymmetricKeyAttributes */ public function hasPublicKeyData(): bool { - return isset($this->_publicKeyData); + return isset($this->publicKeyData); } /** @@ -276,7 +276,7 @@ public function publicKeyData(): BitString if (! $this->hasPublicKeyData()) { throw new LogicException('No explicit public key.'); } - return $this->_publicKeyData; + return $this->publicKeyData; } /** @@ -286,14 +286,14 @@ public function toASN1(): Sequence { $elements = [ Integer::create($this->version), - $this->_algo->toASN1(), - OctetString::create($this->_privateKeyData), + $this->algo->toASN1(), + OctetString::create($this->privateKeyData), ]; - if ($this->_attributes !== null) { - $elements[] = ImplicitlyTaggedType::create(0, $this->_attributes->toASN1()); + if ($this->attributes !== null) { + $elements[] = ImplicitlyTaggedType::create(0, $this->attributes->toASN1()); } - if ($this->_publicKeyData !== null) { - $elements[] = ImplicitlyTaggedType::create(1, $this->_publicKeyData); + if ($this->publicKeyData !== null) { + $elements[] = ImplicitlyTaggedType::create(1, $this->publicKeyData); } return Sequence::create(...$elements); } diff --git a/src/CryptoTypes/Asymmetric/PublicKeyInfo.php b/src/CryptoTypes/Asymmetric/PublicKeyInfo.php index 30303e09..9e199628 100644 --- a/src/CryptoTypes/Asymmetric/PublicKeyInfo.php +++ b/src/CryptoTypes/Asymmetric/PublicKeyInfo.php @@ -30,15 +30,20 @@ final class PublicKeyInfo { /** - * @param AlgorithmIdentifierType $_algo Algorithm - * @param BitString $_publicKey Public key data + * @param AlgorithmIdentifierType $algo Algorithm + * @param BitString $publicKey Public key data */ - public function __construct( - protected AlgorithmIdentifierType $_algo, - protected BitString $_publicKey + private function __construct( + private readonly AlgorithmIdentifierType $algo, + private readonly BitString $publicKey ) { } + public static function create(AlgorithmIdentifierType $algo, BitString $publicKey): self + { + return new self($algo, $publicKey); + } + /** * Initialize from ASN.1. */ @@ -47,7 +52,7 @@ public static function fromASN1(Sequence $seq): self $algo = AlgorithmIdentifier::fromASN1($seq->at(0)->asSequence()); $key = $seq->at(1) ->asBitString(); - return new self($algo, $key); + return self::create($algo, $key); } /** @@ -55,7 +60,7 @@ public static function fromASN1(Sequence $seq): self */ public static function fromPublicKey(PublicKey $key): self { - return new self($key->algorithmIdentifier(), $key->subjectPublicKey()); + return self::create($key->algorithmIdentifier(), $key->subjectPublicKey()); } /** @@ -83,7 +88,7 @@ public static function fromDER(string $data): self */ public function algorithmIdentifier(): AlgorithmIdentifierType { - return $this->_algo; + return $this->algo; } /** @@ -91,7 +96,7 @@ public function algorithmIdentifier(): AlgorithmIdentifierType */ public function publicKeyData(): BitString { - return $this->_publicKey; + return $this->publicKey; } /** @@ -103,26 +108,26 @@ public function publicKey(): PublicKey switch ($algo->oid()) { // RSA case AlgorithmIdentifier::OID_RSA_ENCRYPTION: - return RSAPublicKey::fromDER($this->_publicKey->string()); + return RSAPublicKey::fromDER($this->publicKey->string()); // Elliptic Curve case AlgorithmIdentifier::OID_EC_PUBLIC_KEY: if (! $algo instanceof ECPublicKeyAlgorithmIdentifier) { throw new UnexpectedValueException('Not an EC algorithm.'); } // ECPoint is directly mapped into public key data - return new ECPublicKey($this->_publicKey->string(), $algo->namedCurve()); + return ECPublicKey::create($this->publicKey->string(), $algo->namedCurve()); // Ed25519 case AlgorithmIdentifier::OID_ED25519: - return new Ed25519PublicKey($this->_publicKey->string()); + return Ed25519PublicKey::create($this->publicKey->string()); // X25519 case AlgorithmIdentifier::OID_X25519: - return new X25519PublicKey($this->_publicKey->string()); + return X25519PublicKey::create($this->publicKey->string()); // Ed448 case AlgorithmIdentifier::OID_ED448: - return new Ed448PublicKey($this->_publicKey->string()); + return Ed448PublicKey::create($this->publicKey->string()); // X448 case AlgorithmIdentifier::OID_X448: - return new X448PublicKey($this->_publicKey->string()); + return X448PublicKey::create($this->publicKey->string()); } throw new RuntimeException('Public key ' . $algo->name() . ' not supported.'); } @@ -136,7 +141,7 @@ public function publicKey(): PublicKey */ public function keyIdentifier(): string { - return sha1($this->_publicKey->string(), true); + return sha1($this->publicKey->string(), true); } /** @@ -159,7 +164,7 @@ public function keyIdentifier64(): string */ public function toASN1(): Sequence { - return Sequence::create($this->_algo->toASN1(), $this->_publicKey); + return Sequence::create($this->algo->toASN1(), $this->publicKey); } /** diff --git a/src/CryptoTypes/Asymmetric/RFC8410/Curve25519/Curve25519PublicKey.php b/src/CryptoTypes/Asymmetric/RFC8410/Curve25519/Curve25519PublicKey.php index 2e9f2a45..c4de027e 100644 --- a/src/CryptoTypes/Asymmetric/RFC8410/Curve25519/Curve25519PublicKey.php +++ b/src/CryptoTypes/Asymmetric/RFC8410/Curve25519/Curve25519PublicKey.php @@ -16,13 +16,13 @@ abstract class Curve25519PublicKey extends RFC8410PublicKey { /** - * @param string $public_key Public key data + * @param string $publicKey Public key data */ - public function __construct(string $public_key) + protected function __construct(string $publicKey) { - if (mb_strlen($public_key, '8bit') !== 32) { + if (mb_strlen($publicKey, '8bit') !== 32) { throw new UnexpectedValueException('Curve25519 public key must be exactly 32 bytes.'); } - parent::__construct($public_key); + parent::__construct($publicKey); } } diff --git a/src/CryptoTypes/Asymmetric/RFC8410/Curve25519/Ed25519PrivateKey.php b/src/CryptoTypes/Asymmetric/RFC8410/Curve25519/Ed25519PrivateKey.php index 200dadd0..da7a87f8 100644 --- a/src/CryptoTypes/Asymmetric/RFC8410/Curve25519/Ed25519PrivateKey.php +++ b/src/CryptoTypes/Asymmetric/RFC8410/Curve25519/Ed25519PrivateKey.php @@ -30,7 +30,7 @@ public static function create(string $private_key, ?string $public_key = null): */ public static function fromOctetString(OctetString $str, ?string $public_key = null): self { - return new self($str->string(), $public_key); + return self::create($str->string(), $public_key); } public function algorithmIdentifier(): AlgorithmIdentifierType @@ -43,6 +43,6 @@ public function publicKey(): PublicKey if (! $this->hasPublicKey()) { throw new LogicException('Public key not set.'); } - return new Ed25519PublicKey($this->_publicKeyData); + return Ed25519PublicKey::create($this->_publicKeyData); } } diff --git a/src/CryptoTypes/Asymmetric/RFC8410/Curve25519/Ed25519PublicKey.php b/src/CryptoTypes/Asymmetric/RFC8410/Curve25519/Ed25519PublicKey.php index 04ffdb70..41eb7685 100644 --- a/src/CryptoTypes/Asymmetric/RFC8410/Curve25519/Ed25519PublicKey.php +++ b/src/CryptoTypes/Asymmetric/RFC8410/Curve25519/Ed25519PublicKey.php @@ -14,6 +14,11 @@ */ final class Ed25519PublicKey extends Curve25519PublicKey { + public static function create(string $publicKey): self + { + return new self($publicKey); + } + public function algorithmIdentifier(): AlgorithmIdentifierType { return Ed25519AlgorithmIdentifier::create(); diff --git a/src/CryptoTypes/Asymmetric/RFC8410/Curve25519/X25519PrivateKey.php b/src/CryptoTypes/Asymmetric/RFC8410/Curve25519/X25519PrivateKey.php index a228408e..5d750194 100644 --- a/src/CryptoTypes/Asymmetric/RFC8410/Curve25519/X25519PrivateKey.php +++ b/src/CryptoTypes/Asymmetric/RFC8410/Curve25519/X25519PrivateKey.php @@ -30,7 +30,7 @@ public static function create(string $private_key, ?string $public_key = null): */ public static function fromOctetString(OctetString $str, ?string $public_key = null): self { - return new self($str->string(), $public_key); + return self::create($str->string(), $public_key); } public function algorithmIdentifier(): AlgorithmIdentifierType @@ -43,6 +43,6 @@ public function publicKey(): PublicKey if (! $this->hasPublicKey()) { throw new LogicException('Public key not set.'); } - return new X25519PublicKey($this->_publicKeyData); + return X25519PublicKey::create($this->_publicKeyData); } } diff --git a/src/CryptoTypes/Asymmetric/RFC8410/Curve25519/X25519PublicKey.php b/src/CryptoTypes/Asymmetric/RFC8410/Curve25519/X25519PublicKey.php index f6324fc0..95cad2a2 100644 --- a/src/CryptoTypes/Asymmetric/RFC8410/Curve25519/X25519PublicKey.php +++ b/src/CryptoTypes/Asymmetric/RFC8410/Curve25519/X25519PublicKey.php @@ -14,6 +14,11 @@ */ final class X25519PublicKey extends Curve25519PublicKey { + public static function create(string $publicKey): self + { + return new self($publicKey); + } + public function algorithmIdentifier(): AlgorithmIdentifierType { return X25519AlgorithmIdentifier::create(); diff --git a/src/CryptoTypes/Asymmetric/RFC8410/Curve448/Ed448PrivateKey.php b/src/CryptoTypes/Asymmetric/RFC8410/Curve448/Ed448PrivateKey.php index dbeab112..9675d8aa 100644 --- a/src/CryptoTypes/Asymmetric/RFC8410/Curve448/Ed448PrivateKey.php +++ b/src/CryptoTypes/Asymmetric/RFC8410/Curve448/Ed448PrivateKey.php @@ -48,7 +48,7 @@ public static function create(string $private_key, ?string $public_key = null): */ public static function fromOctetString(OctetString $str, ?string $public_key = null): self { - return new self($str->string(), $public_key); + return self::create($str->string(), $public_key); } public function algorithmIdentifier(): AlgorithmIdentifierType @@ -61,6 +61,6 @@ public function publicKey(): PublicKey if (! $this->hasPublicKey()) { throw new LogicException('Public key not set.'); } - return new Ed448PublicKey($this->_publicKeyData); + return Ed448PublicKey::create($this->_publicKeyData); } } diff --git a/src/CryptoTypes/Asymmetric/RFC8410/Curve448/Ed448PublicKey.php b/src/CryptoTypes/Asymmetric/RFC8410/Curve448/Ed448PublicKey.php index 46e1d05f..f8d1c2c8 100644 --- a/src/CryptoTypes/Asymmetric/RFC8410/Curve448/Ed448PublicKey.php +++ b/src/CryptoTypes/Asymmetric/RFC8410/Curve448/Ed448PublicKey.php @@ -18,14 +18,19 @@ final class Ed448PublicKey extends RFC8410PublicKey { /** - * @param string $public_key Public key data + * @param string $publicKey Public key data */ - public function __construct(string $public_key) + private function __construct(string $publicKey) { - if (mb_strlen($public_key, '8bit') !== 57) { + if (mb_strlen($publicKey, '8bit') !== 57) { throw new UnexpectedValueException('Ed448 public key must be exactly 57 bytes.'); } - parent::__construct($public_key); + parent::__construct($publicKey); + } + + public static function create(string $publicKey): self + { + return new self($publicKey); } public function algorithmIdentifier(): AlgorithmIdentifierType diff --git a/src/CryptoTypes/Asymmetric/RFC8410/Curve448/X448PrivateKey.php b/src/CryptoTypes/Asymmetric/RFC8410/Curve448/X448PrivateKey.php index 69b7eea7..4cd12d3a 100644 --- a/src/CryptoTypes/Asymmetric/RFC8410/Curve448/X448PrivateKey.php +++ b/src/CryptoTypes/Asymmetric/RFC8410/Curve448/X448PrivateKey.php @@ -48,7 +48,7 @@ public static function create(string $private_key, ?string $public_key = null): */ public static function fromOctetString(OctetString $str, ?string $public_key = null): self { - return new self($str->string(), $public_key); + return self::create($str->string(), $public_key); } public function algorithmIdentifier(): AlgorithmIdentifierType @@ -61,6 +61,6 @@ public function publicKey(): PublicKey if (! $this->hasPublicKey()) { throw new LogicException('Public key not set.'); } - return new X448PublicKey($this->_publicKeyData); + return X448PublicKey::create($this->_publicKeyData); } } diff --git a/src/CryptoTypes/Asymmetric/RFC8410/Curve448/X448PublicKey.php b/src/CryptoTypes/Asymmetric/RFC8410/Curve448/X448PublicKey.php index a3859123..3eab381a 100644 --- a/src/CryptoTypes/Asymmetric/RFC8410/Curve448/X448PublicKey.php +++ b/src/CryptoTypes/Asymmetric/RFC8410/Curve448/X448PublicKey.php @@ -18,14 +18,19 @@ final class X448PublicKey extends RFC8410PublicKey { /** - * @param string $public_key Public key data + * @param string $publicKey Public key data */ - public function __construct(string $public_key) + private function __construct(string $publicKey) { - if (mb_strlen($public_key, '8bit') !== 56) { + if (mb_strlen($publicKey, '8bit') !== 56) { throw new UnexpectedValueException('X448 public key must be exactly 56 bytes.'); } - parent::__construct($public_key); + parent::__construct($publicKey); + } + + public static function create(string $publicKey): self + { + return new self($publicKey); } public function algorithmIdentifier(): AlgorithmIdentifierType diff --git a/src/CryptoTypes/Asymmetric/RFC8410/RFC8410PublicKey.php b/src/CryptoTypes/Asymmetric/RFC8410/RFC8410PublicKey.php index 692c5a86..2d497733 100644 --- a/src/CryptoTypes/Asymmetric/RFC8410/RFC8410PublicKey.php +++ b/src/CryptoTypes/Asymmetric/RFC8410/RFC8410PublicKey.php @@ -18,9 +18,9 @@ abstract class RFC8410PublicKey extends PublicKey { /** - * @param string $_publicKey Public key data + * @param string $publicKey Public key data */ - public function __construct(protected string $_publicKey) + protected function __construct(private readonly string $publicKey) { } @@ -31,6 +31,6 @@ public function toDER(): string public function subjectPublicKey(): BitString { - return BitString::create($this->_publicKey); + return BitString::create($this->publicKey); } } diff --git a/src/CryptoTypes/Asymmetric/RSA/RSAPrivateKey.php b/src/CryptoTypes/Asymmetric/RSA/RSAPrivateKey.php index b18e9d07..cd98166a 100644 --- a/src/CryptoTypes/Asymmetric/RSA/RSAPrivateKey.php +++ b/src/CryptoTypes/Asymmetric/RSA/RSAPrivateKey.php @@ -12,7 +12,6 @@ use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Feature\AlgorithmIdentifierType; use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PrivateKey; use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PublicKey; -use function strval; use UnexpectedValueException; /** @@ -23,65 +22,38 @@ final class RSAPrivateKey extends PrivateKey { /** - * Modulus as a base 10 integer. - */ - protected string $_modulus; - - /** - * Public exponent as a base 10 integer. - */ - protected string $_publicExponent; - - /** - * Private exponent as a base 10 integer. - */ - protected string $_privateExponent; - - /** - * First prime factor as a base 10 integer. - */ - protected string $_prime1; - - /** - * Second prime factor as a base 10 integer. - */ - protected string $_prime2; - - /** - * First factor exponent as a base 10 integer. - */ - protected string $_exponent1; - - /** - * Second factor exponent as a base 10 integer. - */ - protected string $_exponent2; - - /** - * CRT coefficient of the second factor as a base 10 integer. - */ - protected string $_coefficient; - - /** - * @param int|string $n Modulus - * @param int|string $e Public exponent - * @param int|string $d Private exponent - * @param int|string $p First prime factor - * @param int|string $q Second prime factor - * @param int|string $dp First factor exponent - * @param int|string $dq Second factor exponent - * @param int|string $qi CRT coefficient of the second factor - */ - public function __construct($n, $e, $d, $p, $q, $dp, $dq, $qi) - { - $this->_modulus = strval($n); - $this->_publicExponent = strval($e); - $this->_privateExponent = strval($d); - $this->_prime1 = strval($p); - $this->_prime2 = strval($q); - $this->_exponent1 = strval($dp); - $this->_exponent2 = strval($dq); - $this->_coefficient = strval($qi); + * @param string $modulus Modulus + * @param string $publicExponent Public exponent + * @param string $privateExponent Private exponent + * @param string $prime1 First prime factor + * @param string $prime2 Second prime factor + * @param string $exponent1 First factor exponent + * @param string $exponent2 Second factor exponent + * @param string $coefficient CRT coefficient of the second factor + */ + private function __construct( + private readonly string $modulus, + private readonly string $publicExponent, + private readonly string $privateExponent, + private readonly string $prime1, + private readonly string $prime2, + private readonly string $exponent1, + private readonly string $exponent2, + private readonly string $coefficient + ) { + } + + public static function create( + string $n, + string $e, + string $d, + string $p, + string $q, + string $dp, + string $dq, + string $qi + ): self { + return new self($n, $e, $d, $p, $q, $dp, $dq, $qi); } /** @@ -96,7 +68,7 @@ public static function fromASN1(Sequence $seq): self throw new UnexpectedValueException('Version must be 0.'); } // helper function get integer from given index - $get_int = fn ($idx) => $seq->at($idx) + $get_int = static fn ($idx) => $seq->at($idx) ->asInteger() ->number(); $n = $get_int(1); @@ -107,7 +79,7 @@ public static function fromASN1(Sequence $seq): self $dp = $get_int(6); $dq = $get_int(7); $qi = $get_int(8); - return new self($n, $e, $d, $p, $q, $dp, $dq, $qi); + return self::create($n, $e, $d, $p, $q, $dp, $dq, $qi); } /** @@ -137,7 +109,7 @@ public static function fromPEM(PEM $pem): self */ public function modulus(): string { - return $this->_modulus; + return $this->modulus; } /** @@ -147,7 +119,7 @@ public function modulus(): string */ public function publicExponent(): string { - return $this->_publicExponent; + return $this->publicExponent; } /** @@ -157,7 +129,7 @@ public function publicExponent(): string */ public function privateExponent(): string { - return $this->_privateExponent; + return $this->privateExponent; } /** @@ -167,7 +139,7 @@ public function privateExponent(): string */ public function prime1(): string { - return $this->_prime1; + return $this->prime1; } /** @@ -177,7 +149,7 @@ public function prime1(): string */ public function prime2(): string { - return $this->_prime2; + return $this->prime2; } /** @@ -187,7 +159,7 @@ public function prime2(): string */ public function exponent1(): string { - return $this->_exponent1; + return $this->exponent1; } /** @@ -197,7 +169,7 @@ public function exponent1(): string */ public function exponent2(): string { - return $this->_exponent2; + return $this->exponent2; } /** @@ -207,7 +179,7 @@ public function exponent2(): string */ public function coefficient(): string { - return $this->_coefficient; + return $this->coefficient; } public function algorithmIdentifier(): AlgorithmIdentifierType @@ -220,7 +192,7 @@ public function algorithmIdentifier(): AlgorithmIdentifierType */ public function publicKey(): PublicKey { - return new RSAPublicKey($this->_modulus, $this->_publicExponent); + return RSAPublicKey::create($this->modulus, $this->publicExponent); } /** @@ -230,14 +202,14 @@ public function toASN1(): Sequence { return Sequence::create( Integer::create(0), - Integer::create($this->_modulus), - Integer::create($this->_publicExponent), - Integer::create($this->_privateExponent), - Integer::create($this->_prime1), - Integer::create($this->_prime2), - Integer::create($this->_exponent1), - Integer::create($this->_exponent2), - Integer::create($this->_coefficient) + Integer::create($this->modulus), + Integer::create($this->publicExponent), + Integer::create($this->privateExponent), + Integer::create($this->prime1), + Integer::create($this->prime2), + Integer::create($this->exponent1), + Integer::create($this->exponent2), + Integer::create($this->coefficient) ); } diff --git a/src/CryptoTypes/Asymmetric/RSA/RSAPublicKey.php b/src/CryptoTypes/Asymmetric/RSA/RSAPublicKey.php index d2899404..86f0c1ac 100644 --- a/src/CryptoTypes/Asymmetric/RSA/RSAPublicKey.php +++ b/src/CryptoTypes/Asymmetric/RSA/RSAPublicKey.php @@ -13,7 +13,6 @@ use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Feature\AlgorithmIdentifierType; use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PublicKey; use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PublicKeyInfo; -use function strval; use UnexpectedValueException; /** @@ -23,24 +22,15 @@ */ final class RSAPublicKey extends PublicKey { - /** - * Modulus as a base 10 integer. - */ - protected string $_modulus; - - /** - * Public exponent as a base 10 integer. - */ - protected string $_publicExponent; + private function __construct( + private readonly string $modulus, + private readonly string $publicExponent + ) { + } - /** - * @param int|string $n Modulus - * @param int|string $e Public exponent - */ - public function __construct($n, $e) + public static function create(string $modulus, string $publicExponent): self { - $this->_modulus = strval($n); - $this->_publicExponent = strval($e); + return new self($modulus, $publicExponent); } /** @@ -54,7 +44,7 @@ public static function fromASN1(Sequence $seq): self $e = $seq->at(1) ->asInteger() ->number(); - return new self($n, $e); + return self::create($n, $e); } /** @@ -92,7 +82,7 @@ public static function fromPEM(PEM $pem): self */ public function modulus(): string { - return $this->_modulus; + return $this->modulus; } /** @@ -102,7 +92,7 @@ public function modulus(): string */ public function publicExponent(): string { - return $this->_publicExponent; + return $this->publicExponent; } public function algorithmIdentifier(): AlgorithmIdentifierType @@ -115,7 +105,7 @@ public function algorithmIdentifier(): AlgorithmIdentifierType */ public function toASN1(): Sequence { - return Sequence::create(Integer::create($this->_modulus), Integer::create($this->_publicExponent)); + return Sequence::create(Integer::create($this->modulus), Integer::create($this->publicExponent)); } public function toDER(): string diff --git a/src/CryptoTypes/Signature/ECSignature.php b/src/CryptoTypes/Signature/ECSignature.php index 2dc49b52..d9b4d0dd 100644 --- a/src/CryptoTypes/Signature/ECSignature.php +++ b/src/CryptoTypes/Signature/ECSignature.php @@ -8,7 +8,6 @@ use SpomkyLabs\Pki\ASN1\Type\Primitive\BitString; use SpomkyLabs\Pki\ASN1\Type\Primitive\Integer; use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType; -use function strval; /** * Implements ECDSA signature value. @@ -19,24 +18,15 @@ */ final class ECSignature extends Signature { - /** - * r-value as a base 10 integer. - */ - protected string $_r; - - /** - * s-value as a base 10 integer. - */ - protected string $_s; + private function __construct( + private readonly string $r, + private readonly string $s + ) { + } - /** - * @param int|string $r Signature's `r` value - * @param int|string $s Signature's `s` value - */ - public function __construct($r, $s) + public static function create(string $r, string $s): self { - $this->_r = strval($r); - $this->_s = strval($s); + return new self($r, $s); } /** @@ -50,7 +40,7 @@ public static function fromASN1(Sequence $seq): self $s = $seq->at(1) ->asInteger() ->number(); - return new self($r, $s); + return self::create($r, $s); } /** @@ -68,7 +58,7 @@ public static function fromDER(string $data): self */ public function r(): string { - return $this->_r; + return $this->r; } /** @@ -78,7 +68,7 @@ public function r(): string */ public function s(): string { - return $this->_s; + return $this->s; } /** @@ -86,7 +76,7 @@ public function s(): string */ public function toASN1(): Sequence { - return Sequence::create(Integer::create($this->_r), Integer::create($this->_s)); + return Sequence::create(Integer::create($this->r), Integer::create($this->s)); } /** diff --git a/src/CryptoTypes/Signature/Ed25519Signature.php b/src/CryptoTypes/Signature/Ed25519Signature.php index 31989517..3cbec3bf 100644 --- a/src/CryptoTypes/Signature/Ed25519Signature.php +++ b/src/CryptoTypes/Signature/Ed25519Signature.php @@ -20,18 +20,23 @@ final class Ed25519Signature extends Signature /** * Signature value. */ - private readonly string $_signature; + private readonly string $signature; - public function __construct(string $signature) + private function __construct(string $signature) { if (mb_strlen($signature, '8bit') !== 64) { throw new InvalidArgumentException('Ed25519 signature must be 64 octets.'); } - $this->_signature = $signature; + $this->signature = $signature; + } + + public static function create(string $signature): self + { + return new self($signature); } public function bitString(): BitString { - return BitString::create($this->_signature); + return BitString::create($this->signature); } } diff --git a/src/CryptoTypes/Signature/Ed448Signature.php b/src/CryptoTypes/Signature/Ed448Signature.php index 09226593..7e78eeb3 100644 --- a/src/CryptoTypes/Signature/Ed448Signature.php +++ b/src/CryptoTypes/Signature/Ed448Signature.php @@ -20,18 +20,23 @@ final class Ed448Signature extends Signature /** * Signature value. */ - private readonly string $_signature; + private readonly string $signature; - public function __construct(string $signature) + private function __construct(string $signature) { if (mb_strlen($signature, '8bit') !== 114) { throw new InvalidArgumentException('Ed448 signature must be 114 octets.'); } - $this->_signature = $signature; + $this->signature = $signature; + } + + public static function create(string $signature): self + { + return new self($signature); } public function bitString(): BitString { - return BitString::create($this->_signature); + return BitString::create($this->signature); } } diff --git a/src/CryptoTypes/Signature/GenericSignature.php b/src/CryptoTypes/Signature/GenericSignature.php index 7dbca8df..9487f6f1 100644 --- a/src/CryptoTypes/Signature/GenericSignature.php +++ b/src/CryptoTypes/Signature/GenericSignature.php @@ -13,25 +13,30 @@ final class GenericSignature extends Signature { /** - * @param BitString $_signature Signature value - * @param AlgorithmIdentifierType $_signatureAlgorithm Algorithm identifier + * @param BitString $signature Signature value + * @param AlgorithmIdentifierType $signatureAlgorithm Algorithm identifier */ - public function __construct( - private readonly BitString $_signature, - private readonly AlgorithmIdentifierType $_signatureAlgorithm + private function __construct( + private readonly BitString $signature, + private readonly AlgorithmIdentifierType $signatureAlgorithm ) { } + public static function create(BitString $signature, AlgorithmIdentifierType $signatureAlgorithm): self + { + return new self($signature, $signatureAlgorithm); + } + /** * Get the signature algorithm. */ public function signatureAlgorithm(): AlgorithmIdentifierType { - return $this->_signatureAlgorithm; + return $this->signatureAlgorithm; } public function bitString(): BitString { - return $this->_signature; + return $this->signature; } } diff --git a/src/CryptoTypes/Signature/Signature.php b/src/CryptoTypes/Signature/Signature.php index 204354c7..c164b8cc 100644 --- a/src/CryptoTypes/Signature/Signature.php +++ b/src/CryptoTypes/Signature/Signature.php @@ -36,11 +36,11 @@ public static function fromSignatureData(string $data, AlgorithmIdentifierType $ return ECSignature::fromDER($data); } if ($algo instanceof Ed25519AlgorithmIdentifier) { - return new Ed25519Signature($data); + return Ed25519Signature::create($data); } if ($algo instanceof Ed448AlgorithmIdentifier) { - return new Ed448Signature($data); + return Ed448Signature::create($data); } - return new GenericSignature(BitString::create($data), $algo); + return GenericSignature::create(BitString::create($data), $algo); } } diff --git a/src/X501/ASN1/Attribute.php b/src/X501/ASN1/Attribute.php index ee6feec5..1185f720 100644 --- a/src/X501/ASN1/Attribute.php +++ b/src/X501/ASN1/Attribute.php @@ -13,7 +13,6 @@ use SpomkyLabs\Pki\ASN1\Type\Constructed\Set; use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType; use SpomkyLabs\Pki\X501\ASN1\AttributeValue\AttributeValue; -use SpomkyLabs\Pki\X501\ASN1\Feature\TypedAttribute; /** * Implements *Attribute* ASN.1 type. @@ -22,14 +21,17 @@ */ final class Attribute implements Countable, IteratorAggregate { - use TypedAttribute; + /** + * Attribute type. + */ + private readonly AttributeType $type; /** * Attribute values. * * @var AttributeValue[] */ - protected array $_values; + private readonly array $values; /** * @param AttributeType $type Attribute type @@ -43,8 +45,8 @@ private function __construct(AttributeType $type, AttributeValue ...$values) throw new LogicException('Attribute OID mismatch.'); } } - $this->_type = $type; - $this->_values = $values; + $this->type = $type; + $this->values = $values; } public static function create(AttributeType $type, AttributeValue ...$values): self @@ -59,7 +61,7 @@ public static function fromASN1(Sequence $seq): self { $type = AttributeType::fromASN1($seq->at(0)->asObjectIdentifier()); $values = array_map( - fn (UnspecifiedType $el) => AttributeValue::fromASN1ByOID($type->oid(), $el), + static fn (UnspecifiedType $el) => AttributeValue::fromASN1ByOID($type->oid(), $el), $seq->at(1) ->asSet() ->elements() @@ -88,10 +90,10 @@ public static function fromAttributeValues(AttributeValue ...$values): self */ public function first(): AttributeValue { - if (count($this->_values) === 0) { + if (count($this->values) === 0) { throw new LogicException('Attribute contains no values.'); } - return $this->_values[0]; + return $this->values[0]; } /** @@ -101,7 +103,7 @@ public function first(): AttributeValue */ public function values(): array { - return $this->_values; + return $this->values; } /** @@ -109,9 +111,9 @@ public function values(): array */ public function toASN1(): Sequence { - $values = array_map(static fn (AttributeValue $value) => $value->toASN1(), $this->_values); + $values = array_map(static fn (AttributeValue $value) => $value->toASN1(), $this->values); $valueset = Set::create(...$values); - return Sequence::create($this->_type->toASN1(), $valueset->sortedSetOf()); + return Sequence::create($this->type->toASN1(), $valueset->sortedSetOf()); } /** @@ -139,7 +141,7 @@ function (AttributeValue $value) use ($cls) { } return $value; }, - $this->_values + $this->values ); return self::fromAttributeValues(...$values); } @@ -149,7 +151,7 @@ function (AttributeValue $value) use ($cls) { */ public function count(): int { - return count($this->_values); + return count($this->values); } /** @@ -157,6 +159,22 @@ public function count(): int */ public function getIterator(): ArrayIterator { - return new ArrayIterator($this->_values); + return new ArrayIterator($this->values); + } + + /** + * Get attribute type. + */ + public function type(): AttributeType + { + return $this->type; + } + + /** + * Get OID of the attribute. + */ + public function oid(): string + { + return $this->type->oid(); } } diff --git a/src/X501/ASN1/AttributeTypeAndValue.php b/src/X501/ASN1/AttributeTypeAndValue.php index 65ceaac3..6bde15ba 100644 --- a/src/X501/ASN1/AttributeTypeAndValue.php +++ b/src/X501/ASN1/AttributeTypeAndValue.php @@ -6,7 +6,6 @@ use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence; use SpomkyLabs\Pki\X501\ASN1\AttributeValue\AttributeValue; -use SpomkyLabs\Pki\X501\ASN1\Feature\TypedAttribute; use Stringable; /** @@ -16,17 +15,14 @@ */ final class AttributeTypeAndValue implements Stringable { - use TypedAttribute; - /** * @param AttributeType $type Attribute type - * @param AttributeValue $_value Attribute value + * @param AttributeValue $value Attribute value */ - public function __construct( - AttributeType $type, - protected AttributeValue $_value + private function __construct( + private readonly AttributeType $type, + private readonly AttributeValue $value ) { - $this->_type = $type; } public function __toString(): string @@ -34,6 +30,11 @@ public function __toString(): string return $this->toString(); } + public static function create(AttributeType $type, AttributeValue $value): self + { + return new self($type, $value); + } + /** * Initialize from ASN.1. */ @@ -41,7 +42,7 @@ public static function fromASN1(Sequence $seq): self { $type = AttributeType::fromASN1($seq->at(0)->asObjectIdentifier()); $value = AttributeValue::fromASN1ByOID($type->oid(), $seq->at(1)); - return new self($type, $value); + return self::create($type, $value); } /** @@ -51,7 +52,7 @@ public static function fromASN1(Sequence $seq): self */ public static function fromAttributeValue(AttributeValue $value): self { - return new self(AttributeType::create($value->oid()), $value); + return self::create(AttributeType::create($value->oid()), $value); } /** @@ -59,7 +60,7 @@ public static function fromAttributeValue(AttributeValue $value): self */ public function value(): AttributeValue { - return $this->_value; + return $this->value; } /** @@ -67,7 +68,7 @@ public function value(): AttributeValue */ public function toASN1(): Sequence { - return Sequence::create($this->_type->toASN1(), $this->_value->toASN1()); + return Sequence::create($this->type->toASN1(), $this->value->toASN1()); } /** @@ -77,7 +78,7 @@ public function toASN1(): Sequence */ public function toString(): string { - return $this->_type->typeName() . '=' . $this->_value->rfc2253String(); + return $this->type->typeName() . '=' . $this->value->rfc2253String(); } /** @@ -91,8 +92,24 @@ public function equals(self $other): bool if ($this->oid() !== $other->oid()) { return false; } - $matcher = $this->_value->equalityMatchingRule(); + $matcher = $this->value->equalityMatchingRule(); + + return $matcher->compare($this->value->stringValue(), $other->value->stringValue()) === true; + } - return $matcher->compare($this->_value->stringValue(), $other->_value->stringValue()) === true; + /** + * Get attribute type. + */ + public function type(): AttributeType + { + return $this->type; + } + + /** + * Get OID of the attribute. + */ + public function oid(): string + { + return $this->type->oid(); } } diff --git a/src/X501/ASN1/AttributeValue/CountryNameValue.php b/src/X501/ASN1/AttributeValue/CountryNameValue.php index 9e2fe263..1826c00a 100644 --- a/src/X501/ASN1/AttributeValue/CountryNameValue.php +++ b/src/X501/ASN1/AttributeValue/CountryNameValue.php @@ -30,6 +30,6 @@ public static function create(string $value): self public static function fromASN1(UnspecifiedType $el): self { - return new self($el->asPrintableString()->string()); + return self::create($el->asPrintableString()->string()); } } diff --git a/src/X501/ASN1/AttributeValue/Feature/DirectoryString.php b/src/X501/ASN1/AttributeValue/Feature/DirectoryString.php index a6e66b59..74530f17 100644 --- a/src/X501/ASN1/AttributeValue/Feature/DirectoryString.php +++ b/src/X501/ASN1/AttributeValue/Feature/DirectoryString.php @@ -114,7 +114,7 @@ public function stringValue(): string public function equalityMatchingRule(): MatchingRule { - return new CaseIgnoreMatch($this->_stringTag); + return CaseIgnoreMatch::create($this->_stringTag); } public function rfc2253String(): string diff --git a/src/X501/ASN1/AttributeValue/Feature/PrintableStringValue.php b/src/X501/ASN1/AttributeValue/Feature/PrintableStringValue.php index 45449ed7..c8b31fe2 100644 --- a/src/X501/ASN1/AttributeValue/Feature/PrintableStringValue.php +++ b/src/X501/ASN1/AttributeValue/Feature/PrintableStringValue.php @@ -39,7 +39,7 @@ public function stringValue(): string public function equalityMatchingRule(): MatchingRule { // default to caseIgnoreMatch - return new CaseIgnoreMatch(Element::TYPE_PRINTABLE_STRING); + return CaseIgnoreMatch::create(Element::TYPE_PRINTABLE_STRING); } public function rfc2253String(): string diff --git a/src/X501/ASN1/AttributeValue/SerialNumberValue.php b/src/X501/ASN1/AttributeValue/SerialNumberValue.php index f5fcdb46..0b3027c8 100644 --- a/src/X501/ASN1/AttributeValue/SerialNumberValue.php +++ b/src/X501/ASN1/AttributeValue/SerialNumberValue.php @@ -30,6 +30,6 @@ public static function create(string $value): self public static function fromASN1(UnspecifiedType $el): self { - return new self($el->asPrintableString()->string()); + return self::create($el->asPrintableString()->string()); } } diff --git a/src/X501/ASN1/Feature/TypedAttribute.php b/src/X501/ASN1/Feature/TypedAttribute.php deleted file mode 100644 index b8acbe7c..00000000 --- a/src/X501/ASN1/Feature/TypedAttribute.php +++ /dev/null @@ -1,34 +0,0 @@ -_type; - } - - /** - * Get OID of the attribute. - */ - public function oid(): string - { - return $this->_type->oid(); - } -} diff --git a/src/X501/ASN1/Name.php b/src/X501/ASN1/Name.php index 648da04e..4b588354 100644 --- a/src/X501/ASN1/Name.php +++ b/src/X501/ASN1/Name.php @@ -30,14 +30,14 @@ final class Name implements Countable, IteratorAggregate, Stringable * * @var RDN[] */ - private readonly array $_rdns; + private readonly array $rdns; /** * @param RDN ...$rdns RDN components */ - public function __construct(RDN ...$rdns) + private function __construct(RDN ...$rdns) { - $this->_rdns = $rdns; + $this->rdns = $rdns; } public function __toString(): string @@ -45,13 +45,18 @@ public function __toString(): string return $this->toString(); } + public static function create(RDN ...$rdns): self + { + return new self(...$rdns); + } + /** * Initialize from ASN.1. */ public static function fromASN1(Sequence $seq): self { $rdns = array_map(static fn (UnspecifiedType $el) => RDN::fromASN1($el->asSet()), $seq->elements()); - return new self(...$rdns); + return self::create(...$rdns); } /** @@ -73,11 +78,11 @@ public static function fromString(string $str): self $el = AttributeType::asn1StringForType($type->oid(), $val); } $value = AttributeValue::fromASN1ByOID($type->oid(), $el->asUnspecified()); - $attribs[] = new AttributeTypeAndValue($type, $value); + $attribs[] = AttributeTypeAndValue::create($type, $value); } - $rdns[] = new RDN(...$attribs); + $rdns[] = RDN::create(...$attribs); } - return new self(...$rdns); + return self::create(...$rdns); } /** @@ -85,7 +90,7 @@ public static function fromString(string $str): self */ public function toASN1(): Sequence { - $elements = array_map(static fn (RDN $rdn) => $rdn->toASN1(), $this->_rdns); + $elements = array_map(static fn (RDN $rdn) => $rdn->toASN1(), $this->rdns); return Sequence::create(...$elements); } @@ -96,7 +101,7 @@ public function toASN1(): Sequence */ public function toString(): string { - $parts = array_map(static fn (RDN $rdn) => $rdn->toString(), array_reverse($this->_rdns)); + $parts = array_map(static fn (RDN $rdn) => $rdn->toString(), array_reverse($this->rdns)); return implode(',', $parts); } @@ -116,8 +121,8 @@ public function equals(self $other): bool return false; } for ($i = count($this) - 1; $i >= 0; --$i) { - $rdn1 = $this->_rdns[$i]; - $rdn2 = $other->_rdns[$i]; + $rdn1 = $this->rdns[$i]; + $rdn2 = $other->rdns[$i]; if (! $rdn1->equals($rdn2)) { return false; } @@ -132,7 +137,7 @@ public function equals(self $other): bool */ public function all(): array { - return $this->_rdns; + return $this->rdns; } /** @@ -147,7 +152,7 @@ public function all(): array public function firstValueOf(string $name): AttributeValue { $oid = AttributeType::attrNameToOID($name); - foreach ($this->_rdns as $rdn) { + foreach ($this->rdns as $rdn) { $tvs = $rdn->allOf($oid); if (count($tvs) > 1) { throw new RangeException("RDN with multiple {$name} attributes."); @@ -164,7 +169,7 @@ public function firstValueOf(string $name): AttributeValue */ public function count(): int { - return count($this->_rdns); + return count($this->rdns); } /** @@ -175,7 +180,7 @@ public function count(): int public function countOfType(string $name): int { $oid = AttributeType::attrNameToOID($name); - return array_sum(array_map(static fn (RDN $rdn): int => count($rdn->allOf($oid)), $this->_rdns)); + return array_sum(array_map(static fn (RDN $rdn): int => count($rdn->allOf($oid)), $this->rdns)); } /** @@ -183,6 +188,6 @@ public function countOfType(string $name): int */ public function getIterator(): ArrayIterator { - return new ArrayIterator($this->_rdns); + return new ArrayIterator($this->rdns); } } diff --git a/src/X501/ASN1/RDN.php b/src/X501/ASN1/RDN.php index ca8e9ca8..ec159b35 100644 --- a/src/X501/ASN1/RDN.php +++ b/src/X501/ASN1/RDN.php @@ -31,7 +31,7 @@ final class RDN implements Countable, IteratorAggregate, Stringable /** * @param AttributeTypeAndValue ...$attribs One or more attributes */ - public function __construct(AttributeTypeAndValue ...$attribs) + private function __construct(AttributeTypeAndValue ...$attribs) { if (count($attribs) === 0) { throw new UnexpectedValueException('RDN must have at least one AttributeTypeAndValue.'); @@ -44,6 +44,11 @@ public function __toString(): string return $this->toString(); } + public static function create(AttributeTypeAndValue ...$attribs): self + { + return new self(...$attribs); + } + /** * Convenience method to initialize RDN from AttributeValue objects. * @@ -52,12 +57,12 @@ public function __toString(): string public static function fromAttributeValues(AttributeValue ...$values): self { $attribs = array_map( - static fn (AttributeValue $value) => new AttributeTypeAndValue(AttributeType::create( + static fn (AttributeValue $value) => AttributeTypeAndValue::create(AttributeType::create( $value->oid() ), $value), $values ); - return new self(...$attribs); + return self::create(...$attribs); } /** @@ -69,7 +74,7 @@ public static function fromASN1(Set $set): self static fn (UnspecifiedType $el) => AttributeTypeAndValue::fromASN1($el->asSequence()), $set->elements() ); - return new self(...$attribs); + return self::create(...$attribs); } /** diff --git a/src/X501/MatchingRule/CaseExactMatch.php b/src/X501/MatchingRule/CaseExactMatch.php index e4c5dd68..19ead755 100644 --- a/src/X501/MatchingRule/CaseExactMatch.php +++ b/src/X501/MatchingRule/CaseExactMatch.php @@ -14,10 +14,15 @@ final class CaseExactMatch extends StringPrepMatchingRule { /** - * @param int $string_type ASN.1 string type tag + * @param int $stringType ASN.1 string type tag */ - public function __construct(int $string_type) + private function __construct(int $stringType) { - parent::__construct(StringPreparer::forStringType($string_type)); + parent::__construct(StringPreparer::forStringType($stringType)); + } + + public static function create(int $stringType): self + { + return new self($stringType); } } diff --git a/src/X501/MatchingRule/CaseIgnoreMatch.php b/src/X501/MatchingRule/CaseIgnoreMatch.php index 45e350a1..0f187d5e 100644 --- a/src/X501/MatchingRule/CaseIgnoreMatch.php +++ b/src/X501/MatchingRule/CaseIgnoreMatch.php @@ -14,12 +14,17 @@ final class CaseIgnoreMatch extends StringPrepMatchingRule { /** - * @param int $string_type ASN.1 string type tag + * @param int $stringType ASN.1 string type tag */ - public function __construct(int $string_type) + private function __construct(int $stringType) { parent::__construct( - StringPreparer::forStringType($string_type)->withCaseFolding(true) + StringPreparer::forStringType($stringType)->withCaseFolding(true) ); } + + public static function create(int $stringType): self + { + return new self($stringType); + } } diff --git a/src/X501/MatchingRule/StringPrepMatchingRule.php b/src/X501/MatchingRule/StringPrepMatchingRule.php index 5b83a631..2e5af187 100644 --- a/src/X501/MatchingRule/StringPrepMatchingRule.php +++ b/src/X501/MatchingRule/StringPrepMatchingRule.php @@ -11,18 +11,15 @@ */ abstract class StringPrepMatchingRule extends MatchingRule { - public function __construct( - /** - * String preparer. - */ - protected StringPreparer $_prep + protected function __construct( + private readonly StringPreparer $preparer ) { } public function compare(string $assertion, string $value): ?bool { - $assertion = $this->_prep->prepare($assertion); - $value = $this->_prep->prepare($value); + $assertion = $this->preparer->prepare($assertion); + $value = $this->preparer->prepare($value); return strcmp($assertion, $value) === 0; } } diff --git a/src/X501/StringPrep/MapStep.php b/src/X501/StringPrep/MapStep.php index e218ada7..b361f96b 100644 --- a/src/X501/StringPrep/MapStep.php +++ b/src/X501/StringPrep/MapStep.php @@ -14,19 +14,24 @@ final class MapStep implements PrepareStep { /** - * @param bool $_fold Whether to apply case folding + * @param bool $fold Whether to apply case folding */ - public function __construct(protected bool $_fold = false) + private function __construct(protected bool $fold) { } + public static function create(bool $fold = false): self + { + return new self($fold); + } + /** * @param string $string UTF-8 encoded string */ public function apply(string $string): string { // @todo Implement character mappings - if ($this->_fold) { + if ($this->fold) { $string = mb_convert_case($string, MB_CASE_LOWER, 'UTF-8'); } return $string; diff --git a/src/X501/StringPrep/StringPreparer.php b/src/X501/StringPrep/StringPreparer.php index 48718e1c..9d7b0623 100644 --- a/src/X501/StringPrep/StringPreparer.php +++ b/src/X501/StringPrep/StringPreparer.php @@ -43,7 +43,7 @@ public static function forStringType(int $string_type): self { $steps = [ self::STEP_TRANSCODE => TranscodeStep::create($string_type), - self::STEP_MAP => new MapStep(), + self::STEP_MAP => MapStep::create(), self::STEP_NORMALIZE => new NormalizeStep(), self::STEP_PROHIBIT => new ProhibitStep(), self::STEP_CHECK_BIDI => new CheckBidiStep(), @@ -61,7 +61,7 @@ public static function forStringType(int $string_type): self public function withCaseFolding(bool $fold): self { $obj = clone $this; - $obj->_steps[self::STEP_MAP] = new MapStep($fold); + $obj->_steps[self::STEP_MAP] = MapStep::create($fold); return $obj; } diff --git a/src/X509/AttributeCertificate/AttCertIssuer.php b/src/X509/AttributeCertificate/AttCertIssuer.php index 65c01ab1..8dce6afc 100644 --- a/src/X509/AttributeCertificate/AttCertIssuer.php +++ b/src/X509/AttributeCertificate/AttCertIssuer.php @@ -39,7 +39,7 @@ abstract public function identifiesPKC(Certificate $cert): bool; */ public static function fromName(Name $name): self { - return new V2Form(GeneralNames::create(DirectoryName::create($name))); + return V2Form::create(GeneralNames::create(DirectoryName::create($name))); } /** diff --git a/src/X509/AttributeCertificate/AttCertValidityPeriod.php b/src/X509/AttributeCertificate/AttCertValidityPeriod.php index afc5e687..88119bf8 100644 --- a/src/X509/AttributeCertificate/AttCertValidityPeriod.php +++ b/src/X509/AttributeCertificate/AttCertValidityPeriod.php @@ -18,18 +18,17 @@ final class AttCertValidityPeriod { use DateTimeHelper; - public function __construct( - /** - * Not before time. - */ - protected DateTimeImmutable $_notBeforeTime, - /** - * Not after time. - */ - protected DateTimeImmutable $_notAfterTime + private function __construct( + private readonly DateTimeImmutable $notBeforeTime, + private readonly DateTimeImmutable $notAfterTime ) { } + public static function create(DateTimeImmutable $notBeforeTime, DateTimeImmutable $notAfterTime): self + { + return new self($notBeforeTime, $notAfterTime); + } + /** * Initialize from ASN.1. */ @@ -41,7 +40,7 @@ public static function fromASN1(Sequence $seq): self $na = $seq->at(1) ->asGeneralizedTime() ->dateTime(); - return new self($nb, $na); + return self::create($nb, $na); } /** @@ -53,9 +52,9 @@ public static function fromASN1(Sequence $seq): self */ public static function fromStrings(?string $nb_date, ?string $na_date, ?string $tz = null): self { - $nb = self::_createDateTime($nb_date, $tz); - $na = self::_createDateTime($na_date, $tz); - return new self($nb, $na); + $nb = self::createDateTime($nb_date, $tz); + $na = self::createDateTime($na_date, $tz); + return self::create($nb, $na); } /** @@ -63,7 +62,7 @@ public static function fromStrings(?string $nb_date, ?string $na_date, ?string $ */ public function notBeforeTime(): DateTimeImmutable { - return $this->_notBeforeTime; + return $this->notBeforeTime; } /** @@ -71,7 +70,7 @@ public function notBeforeTime(): DateTimeImmutable */ public function notAfterTime(): DateTimeImmutable { - return $this->_notAfterTime; + return $this->notAfterTime; } /** @@ -80,8 +79,8 @@ public function notAfterTime(): DateTimeImmutable public function toASN1(): Sequence { return Sequence::create( - GeneralizedTime::create($this->_notBeforeTime), - GeneralizedTime::create($this->_notAfterTime) + GeneralizedTime::create($this->notBeforeTime), + GeneralizedTime::create($this->notAfterTime) ); } } diff --git a/src/X509/AttributeCertificate/Attribute/AccessIdentityAttributeValue.php b/src/X509/AttributeCertificate/Attribute/AccessIdentityAttributeValue.php index a4271c1c..e40e62ef 100644 --- a/src/X509/AttributeCertificate/Attribute/AccessIdentityAttributeValue.php +++ b/src/X509/AttributeCertificate/Attribute/AccessIdentityAttributeValue.php @@ -17,9 +17,9 @@ final class AccessIdentityAttributeValue extends SvceAuthInfo { final public const OID = '1.3.6.1.5.5.7.10.2'; - public function __construct(GeneralName $service, GeneralName $ident, ?string $_authInfo = null) + private function __construct(GeneralName $service, GeneralName $ident, ?string $authInfo) { - parent::__construct(self::OID, $service, $ident, $_authInfo); + parent::__construct(self::OID, $service, $ident, $authInfo); } public static function create(GeneralName $service, GeneralName $ident, ?string $_authInfo = null): self @@ -38,6 +38,6 @@ public static function fromASN1(UnspecifiedType $el): static ->asString() ->string(); } - return new static($service, $ident, $auth_info); + return static::create($service, $ident, $auth_info); } } diff --git a/src/X509/AttributeCertificate/Attribute/AuthenticationInfoAttributeValue.php b/src/X509/AttributeCertificate/Attribute/AuthenticationInfoAttributeValue.php index 7c2047ed..7baa8a20 100644 --- a/src/X509/AttributeCertificate/Attribute/AuthenticationInfoAttributeValue.php +++ b/src/X509/AttributeCertificate/Attribute/AuthenticationInfoAttributeValue.php @@ -17,7 +17,7 @@ final class AuthenticationInfoAttributeValue extends SvceAuthInfo { final public const OID = '1.3.6.1.5.5.7.10.1'; - protected function __construct(GeneralName $service, GeneralName $ident, ?string $auth_info = null) + private function __construct(GeneralName $service, GeneralName $ident, ?string $auth_info) { parent::__construct(self::OID, $service, $ident, $auth_info); } @@ -38,6 +38,6 @@ public static function fromASN1(UnspecifiedType $el): static ->asString() ->string(); } - return new static($service, $ident, $auth_info); + return static::create($service, $ident, $auth_info); } } diff --git a/src/X509/AttributeCertificate/Attribute/IetfAttrSyntax.php b/src/X509/AttributeCertificate/Attribute/IetfAttrSyntax.php index 38b22397..5fcabe1c 100644 --- a/src/X509/AttributeCertificate/Attribute/IetfAttrSyntax.php +++ b/src/X509/AttributeCertificate/Attribute/IetfAttrSyntax.php @@ -63,7 +63,7 @@ public static function fromASN1(UnspecifiedType $el): AttributeValue ++$idx; } $values = array_map( - fn (UnspecifiedType $el) => IetfAttrValue::fromASN1($el), + static fn (UnspecifiedType $el) => IetfAttrValue::fromASN1($el), $seq->at($idx) ->asSequence() ->elements() diff --git a/src/X509/AttributeCertificate/Attribute/IetfAttrValue.php b/src/X509/AttributeCertificate/Attribute/IetfAttrValue.php index 30e18502..7b7c1e1c 100644 --- a/src/X509/AttributeCertificate/Attribute/IetfAttrValue.php +++ b/src/X509/AttributeCertificate/Attribute/IetfAttrValue.php @@ -20,21 +20,20 @@ */ final class IetfAttrValue implements Stringable { - public function __construct( - /** - * Value. - */ - protected string $_value, - /** - * Element type tag. - */ - protected int $_type + private function __construct( + private readonly string $value, + private readonly int $type ) { } public function __toString(): string { - return $this->_value; + return $this->value; + } + + public static function create(string $value, int $type): self + { + return new self($value, $type); } /** @@ -43,8 +42,12 @@ public function __toString(): string public static function fromASN1(UnspecifiedType $el): self { return match ($el->tag()) { - Element::TYPE_OCTET_STRING, Element::TYPE_UTF8_STRING => new self($el->asString()->string(), $el->tag()), - Element::TYPE_OBJECT_IDENTIFIER => new self($el->asObjectIdentifier()->oid(), $el->tag()), + Element::TYPE_OCTET_STRING, Element::TYPE_UTF8_STRING => self::create( + $el->asString() + ->string(), + $el->tag() + ), + Element::TYPE_OBJECT_IDENTIFIER => self::create($el->asObjectIdentifier()->oid(), $el->tag()), default => throw new UnexpectedValueException('Type ' . Element::tagToName($el->tag()) . ' not supported.'), }; } @@ -54,7 +57,7 @@ public static function fromASN1(UnspecifiedType $el): self */ public static function fromOctets(string $octets): self { - return new self($octets, Element::TYPE_OCTET_STRING); + return self::create($octets, Element::TYPE_OCTET_STRING); } /** @@ -62,7 +65,7 @@ public static function fromOctets(string $octets): self */ public static function fromString(string $str): self { - return new self($str, Element::TYPE_UTF8_STRING); + return self::create($str, Element::TYPE_UTF8_STRING); } /** @@ -70,7 +73,7 @@ public static function fromString(string $str): self */ public static function fromOID(string $oid): self { - return new self($oid, Element::TYPE_OBJECT_IDENTIFIER); + return self::create($oid, Element::TYPE_OBJECT_IDENTIFIER); } /** @@ -78,7 +81,7 @@ public static function fromOID(string $oid): self */ public function type(): int { - return $this->_type; + return $this->type; } /** @@ -86,7 +89,7 @@ public function type(): int */ public function isOctets(): bool { - return $this->_type === Element::TYPE_OCTET_STRING; + return $this->type === Element::TYPE_OCTET_STRING; } /** @@ -94,7 +97,7 @@ public function isOctets(): bool */ public function isOID(): bool { - return $this->_type === Element::TYPE_OBJECT_IDENTIFIER; + return $this->type === Element::TYPE_OBJECT_IDENTIFIER; } /** @@ -102,12 +105,12 @@ public function isOID(): bool */ public function isString(): bool { - return $this->_type === Element::TYPE_UTF8_STRING; + return $this->type === Element::TYPE_UTF8_STRING; } public function value(): string { - return $this->_value; + return $this->value; } /** @@ -115,11 +118,11 @@ public function value(): string */ public function toASN1(): Element { - return match ($this->_type) { - Element::TYPE_OCTET_STRING => OctetString::create($this->_value), - Element::TYPE_UTF8_STRING => UTF8String::create($this->_value), - Element::TYPE_OBJECT_IDENTIFIER => ObjectIdentifier::create($this->_value), - default => throw new LogicException('Type ' . Element::tagToName($this->_type) . ' not supported.'), + return match ($this->type) { + Element::TYPE_OCTET_STRING => OctetString::create($this->value), + Element::TYPE_UTF8_STRING => UTF8String::create($this->value), + Element::TYPE_OBJECT_IDENTIFIER => ObjectIdentifier::create($this->value), + default => throw new LogicException('Type ' . Element::tagToName($this->type) . ' not supported.'), }; } } diff --git a/src/X509/AttributeCertificate/Attribute/RoleAttributeValue.php b/src/X509/AttributeCertificate/Attribute/RoleAttributeValue.php index c89081c6..6471fb08 100644 --- a/src/X509/AttributeCertificate/Attribute/RoleAttributeValue.php +++ b/src/X509/AttributeCertificate/Attribute/RoleAttributeValue.php @@ -26,16 +26,21 @@ final class RoleAttributeValue extends AttributeValue { /** - * @param GeneralName $_roleName Role name - * @param null|GeneralNames $_roleAuthority Issuing authority + * @param GeneralName $roleName Role name + * @param null|GeneralNames $roleAuthority Issuing authority */ - public function __construct( - protected GeneralName $_roleName, - protected ?GeneralNames $_roleAuthority = null + private function __construct( + private readonly GeneralName $roleName, + private readonly ?GeneralNames $roleAuthority ) { parent::__construct(AttributeType::OID_ROLE); } + public static function create(GeneralName $roleName, ?GeneralNames $roleAuthority = null): self + { + return new self($roleName, $roleAuthority); + } + /** * Initialize from a role string. * @@ -44,7 +49,7 @@ public function __construct( */ public static function fromString(string $role_name, ?GeneralNames $authority = null): self { - return new self(UniformResourceIdentifier::create($role_name), $authority); + return self::create(UniformResourceIdentifier::create($role_name), $authority); } /** @@ -62,7 +67,7 @@ public static function fromASN1(UnspecifiedType $el): AttributeValue ); } $name = GeneralName::fromASN1($seq->getTagged(1)->asExplicit()->asTagged()); - return new self($name, $authority); + return self::create($name, $authority); } /** @@ -70,7 +75,7 @@ public static function fromASN1(UnspecifiedType $el): AttributeValue */ public function hasRoleAuthority(): bool { - return isset($this->_roleAuthority); + return isset($this->roleAuthority); } /** @@ -81,7 +86,7 @@ public function roleAuthority(): GeneralNames if (! $this->hasRoleAuthority()) { throw new LogicException('roleAuthority not set.'); } - return $this->_roleAuthority; + return $this->roleAuthority; } /** @@ -89,16 +94,16 @@ public function roleAuthority(): GeneralNames */ public function roleName(): GeneralName { - return $this->_roleName; + return $this->roleName; } public function toASN1(): Element { $elements = []; - if (isset($this->_roleAuthority)) { - $elements[] = ImplicitlyTaggedType::create(0, $this->_roleAuthority->toASN1()); + if (isset($this->roleAuthority)) { + $elements[] = ImplicitlyTaggedType::create(0, $this->roleAuthority->toASN1()); } - $elements[] = ExplicitlyTaggedType::create(1, $this->_roleName->toASN1()); + $elements[] = ExplicitlyTaggedType::create(1, $this->roleName->toASN1()); return Sequence::create(...$elements); } diff --git a/src/X509/AttributeCertificate/Attribute/SvceAuthInfo.php b/src/X509/AttributeCertificate/Attribute/SvceAuthInfo.php index f28eaf5e..4e4d93cc 100644 --- a/src/X509/AttributeCertificate/Attribute/SvceAuthInfo.php +++ b/src/X509/AttributeCertificate/Attribute/SvceAuthInfo.php @@ -23,9 +23,9 @@ abstract class SvceAuthInfo extends AttributeValue { protected function __construct( string $oid, - protected GeneralName $_service, - protected GeneralName $_ident, - protected ?string $_authInfo = null + private readonly GeneralName $service, + private readonly GeneralName $ident, + private readonly ?string $authInfo = null ) { parent::__construct($oid); } @@ -37,12 +37,12 @@ abstract public static function fromASN1(UnspecifiedType $el): static; */ public function service(): GeneralName { - return $this->_service; + return $this->service; } public function ident(): GeneralName { - return $this->_ident; + return $this->ident; } /** @@ -50,7 +50,7 @@ public function ident(): GeneralName */ public function hasAuthInfo(): bool { - return isset($this->_authInfo); + return isset($this->authInfo); } /** @@ -61,14 +61,14 @@ public function authInfo(): string if (! $this->hasAuthInfo()) { throw new LogicException('authInfo not set.'); } - return $this->_authInfo; + return $this->authInfo; } public function toASN1(): Element { - $elements = [$this->_service->toASN1(), $this->_ident->toASN1()]; - if (isset($this->_authInfo)) { - $elements[] = OctetString::create($this->_authInfo); + $elements = [$this->service->toASN1(), $this->ident->toASN1()]; + if (isset($this->authInfo)) { + $elements[] = OctetString::create($this->authInfo); } return Sequence::create(...$elements); } diff --git a/src/X509/AttributeCertificate/AttributeCertificate.php b/src/X509/AttributeCertificate/AttributeCertificate.php index 738591f4..80e70f2a 100644 --- a/src/X509/AttributeCertificate/AttributeCertificate.php +++ b/src/X509/AttributeCertificate/AttributeCertificate.php @@ -23,19 +23,10 @@ */ final class AttributeCertificate implements Stringable { - public function __construct( - /** - * Attribute certificate info. - */ - protected AttributeCertificateInfo $_acinfo, - /** - * Signature algorithm identifier. - */ - protected SignatureAlgorithmIdentifier $_signatureAlgorithm, - /** - * Signature value. - */ - protected Signature $_signatureValue + private function __construct( + private readonly AttributeCertificateInfo $acInfo, + private readonly SignatureAlgorithmIdentifier $signatureAlgorithm, + private readonly Signature $signatureValue ) { } @@ -48,6 +39,14 @@ public function __toString(): string ->string(); } + public static function create( + AttributeCertificateInfo $acInfo, + SignatureAlgorithmIdentifier $signatureAlgorithm, + Signature $signatureValue + ): self { + return new self($acInfo, $signatureAlgorithm, $signatureValue); + } + /** * Initialize from ASN.1. */ @@ -59,7 +58,7 @@ public static function fromASN1(Sequence $seq): self throw new UnexpectedValueException('Unsupported signature algorithm ' . $algo->oid() . '.'); } $signature = Signature::fromSignatureData($seq->at(2)->asBitString()->string(), $algo); - return new self($acinfo, $algo, $signature); + return self::create($acinfo, $algo, $signature); } /** @@ -86,7 +85,7 @@ public static function fromPEM(PEM $pem): self */ public function acinfo(): AttributeCertificateInfo { - return $this->_acinfo; + return $this->acInfo; } /** @@ -94,7 +93,7 @@ public function acinfo(): AttributeCertificateInfo */ public function signatureAlgorithm(): SignatureAlgorithmIdentifier { - return $this->_signatureAlgorithm; + return $this->signatureAlgorithm; } /** @@ -102,7 +101,7 @@ public function signatureAlgorithm(): SignatureAlgorithmIdentifier */ public function signatureValue(): Signature { - return $this->_signatureValue; + return $this->signatureValue; } /** @@ -111,9 +110,9 @@ public function signatureValue(): Signature public function toASN1(): Sequence { return Sequence::create( - $this->_acinfo->toASN1(), - $this->_signatureAlgorithm->toASN1(), - $this->_signatureValue->bitString() + $this->acInfo->toASN1(), + $this->signatureAlgorithm->toASN1(), + $this->signatureValue->bitString() ); } @@ -141,7 +140,7 @@ public function toPEM(): PEM */ public function isHeldBy(Certificate $cert): bool { - if (! $this->_acinfo->holder()->identifiesPKC($cert)) { + if (! $this->acInfo->holder()->identifiesPKC($cert)) { return false; } return true; @@ -154,7 +153,7 @@ public function isHeldBy(Certificate $cert): bool */ public function isIssuedBy(Certificate $cert): bool { - if (! $this->_acinfo->issuer()->identifiesPKC($cert)) { + if (! $this->acInfo->issuer()->identifiesPKC($cert)) { return false; } return true; @@ -169,8 +168,8 @@ public function isIssuedBy(Certificate $cert): bool public function verify(PublicKeyInfo $pubkey_info, ?Crypto $crypto = null): bool { $crypto ??= Crypto::getDefault(); - $data = $this->_acinfo->toASN1() + $data = $this->acInfo->toASN1() ->toDER(); - return $crypto->verify($data, $this->_signatureValue, $pubkey_info, $this->_signatureAlgorithm); + return $crypto->verify($data, $this->signatureValue, $pubkey_info, $this->signatureAlgorithm); } } diff --git a/src/X509/AttributeCertificate/AttributeCertificateInfo.php b/src/X509/AttributeCertificate/AttributeCertificateInfo.php index 590cf429..e49046ba 100644 --- a/src/X509/AttributeCertificate/AttributeCertificateInfo.php +++ b/src/X509/AttributeCertificate/AttributeCertificateInfo.php @@ -32,42 +32,51 @@ final class AttributeCertificateInfo /** * AC version. */ - private readonly int $_version; + private readonly int $version; /** * Signature algorithm identifier. */ - private ?SignatureAlgorithmIdentifier $_signature = null; + private ?SignatureAlgorithmIdentifier $signature = null; /** * AC serial number as a base 10 integer. */ - private ?string $_serialNumber = null; + private ?string $serialNumber = null; /** * Issuer unique identifier. */ - private ?UniqueIdentifier $_issuerUniqueID = null; + private ?UniqueIdentifier $issuerUniqueID = null; /** * Extensions. */ - private Extensions $_extensions; + private Extensions $extensions; /** - * @param Holder $_holder AC holder - * @param AttCertIssuer $_issuer AC issuer - * @param AttCertValidityPeriod $_attrCertValidityPeriod Validity - * @param Attributes $_attributes Attributes + * @param Holder $holder AC holder + * @param AttCertIssuer $issuer AC issuer + * @param AttCertValidityPeriod $attrCertValidityPeriod Validity + * @param Attributes $attributes Attributes */ - public function __construct( - protected Holder $_holder, - protected AttCertIssuer $_issuer, - protected AttCertValidityPeriod $_attrCertValidityPeriod, - protected Attributes $_attributes + private function __construct( + private Holder $holder, + private AttCertIssuer $issuer, + private AttCertValidityPeriod $attrCertValidityPeriod, + private Attributes $attributes ) { - $this->_version = self::VERSION_2; - $this->_extensions = new Extensions(); + $this->version = self::VERSION_2; + $this->extensions = Extensions::create(); + } + + public static function create( + Holder $holder, + AttCertIssuer $issuer, + AttCertValidityPeriod $attrCertValidityPeriod, + Attributes $attributes + ): self { + return new self($holder, $issuer, $attrCertValidityPeriod, $attributes); } /** @@ -93,14 +102,14 @@ public static function fromASN1(Sequence $seq): self ->number(); $validity = AttCertValidityPeriod::fromASN1($seq->at($idx++)->asSequence()); $attribs = Attributes::fromASN1($seq->at($idx++)->asSequence()); - $obj = new self($holder, $issuer, $validity, $attribs); - $obj->_signature = $signature; - $obj->_serialNumber = $serial; + $obj = self::create($holder, $issuer, $validity, $attribs); + $obj->signature = $signature; + $obj->serialNumber = $serial; if ($seq->has($idx, Element::TYPE_BIT_STRING)) { - $obj->_issuerUniqueID = UniqueIdentifier::fromASN1($seq->at($idx++)->asBitString()); + $obj->issuerUniqueID = UniqueIdentifier::fromASN1($seq->at($idx++)->asBitString()); } if ($seq->has($idx, Element::TYPE_SEQUENCE)) { - $obj->_extensions = Extensions::fromASN1($seq->at($idx++)->asSequence()); + $obj->extensions = Extensions::fromASN1($seq->at($idx++)->asSequence()); } return $obj; } @@ -111,7 +120,7 @@ public static function fromASN1(Sequence $seq): self public function withHolder(Holder $holder): self { $obj = clone $this; - $obj->_holder = $holder; + $obj->holder = $holder; return $obj; } @@ -121,7 +130,7 @@ public function withHolder(Holder $holder): self public function withIssuer(AttCertIssuer $issuer): self { $obj = clone $this; - $obj->_issuer = $issuer; + $obj->issuer = $issuer; return $obj; } @@ -131,7 +140,7 @@ public function withIssuer(AttCertIssuer $issuer): self public function withSignature(SignatureAlgorithmIdentifier $algo): self { $obj = clone $this; - $obj->_signature = $algo; + $obj->signature = $algo; return $obj; } @@ -143,7 +152,7 @@ public function withSignature(SignatureAlgorithmIdentifier $algo): self public function withSerialNumber(int|string $serial): self { $obj = clone $this; - $obj->_serialNumber = strval($serial); + $obj->serialNumber = strval($serial); return $obj; } @@ -169,7 +178,7 @@ public function withRandomSerialNumber(int $size): self public function withValidity(AttCertValidityPeriod $validity): self { $obj = clone $this; - $obj->_attrCertValidityPeriod = $validity; + $obj->attrCertValidityPeriod = $validity; return $obj; } @@ -179,7 +188,7 @@ public function withValidity(AttCertValidityPeriod $validity): self public function withAttributes(Attributes $attribs): self { $obj = clone $this; - $obj->_attributes = $attribs; + $obj->attributes = $attribs; return $obj; } @@ -189,7 +198,7 @@ public function withAttributes(Attributes $attribs): self public function withIssuerUniqueID(UniqueIdentifier $uid): self { $obj = clone $this; - $obj->_issuerUniqueID = $uid; + $obj->issuerUniqueID = $uid; return $obj; } @@ -199,7 +208,7 @@ public function withIssuerUniqueID(UniqueIdentifier $uid): self public function withExtensions(Extensions $extensions): self { $obj = clone $this; - $obj->_extensions = $extensions; + $obj->extensions = $extensions; return $obj; } @@ -211,13 +220,13 @@ public function withExtensions(Extensions $extensions): self public function withAdditionalExtensions(Extension ...$exts): self { $obj = clone $this; - $obj->_extensions = $obj->_extensions->withExtensions(...$exts); + $obj->extensions = $obj->extensions->withExtensions(...$exts); return $obj; } public function version(): int { - return $this->_version; + return $this->version; } /** @@ -225,7 +234,7 @@ public function version(): int */ public function holder(): Holder { - return $this->_holder; + return $this->holder; } /** @@ -233,7 +242,7 @@ public function holder(): Holder */ public function issuer(): AttCertIssuer { - return $this->_issuer; + return $this->issuer; } /** @@ -241,7 +250,7 @@ public function issuer(): AttCertIssuer */ public function hasSignature(): bool { - return $this->_signature !== null; + return $this->signature !== null; } /** @@ -252,7 +261,7 @@ public function signature(): SignatureAlgorithmIdentifier if (! $this->hasSignature()) { throw new LogicException('signature not set.'); } - return $this->_signature; + return $this->signature; } /** @@ -260,7 +269,7 @@ public function signature(): SignatureAlgorithmIdentifier */ public function hasSerialNumber(): bool { - return isset($this->_serialNumber); + return isset($this->serialNumber); } /** @@ -271,7 +280,7 @@ public function serialNumber(): string if (! $this->hasSerialNumber()) { throw new LogicException('serialNumber not set.'); } - return $this->_serialNumber; + return $this->serialNumber; } /** @@ -279,12 +288,12 @@ public function serialNumber(): string */ public function validityPeriod(): AttCertValidityPeriod { - return $this->_attrCertValidityPeriod; + return $this->attrCertValidityPeriod; } public function attributes(): Attributes { - return $this->_attributes; + return $this->attributes; } /** @@ -292,7 +301,7 @@ public function attributes(): Attributes */ public function hasIssuerUniqueID(): bool { - return isset($this->_issuerUniqueID); + return isset($this->issuerUniqueID); } /** @@ -303,12 +312,12 @@ public function issuerUniqueID(): UniqueIdentifier if (! $this->hasIssuerUniqueID()) { throw new LogicException('issuerUniqueID not set.'); } - return $this->_issuerUniqueID; + return $this->issuerUniqueID; } public function extensions(): Extensions { - return $this->_extensions; + return $this->extensions; } /** @@ -316,17 +325,17 @@ public function extensions(): Extensions */ public function toASN1(): Sequence { - $elements = [Integer::create($this->_version), $this->_holder->toASN1(), - $this->_issuer->toASN1(), $this->signature() + $elements = [Integer::create($this->version), $this->holder->toASN1(), + $this->issuer->toASN1(), $this->signature() ->toASN1(), Integer::create($this->serialNumber()), - $this->_attrCertValidityPeriod->toASN1(), - $this->_attributes->toASN1(), ]; - if (isset($this->_issuerUniqueID)) { - $elements[] = $this->_issuerUniqueID->toASN1(); + $this->attrCertValidityPeriod->toASN1(), + $this->attributes->toASN1(), ]; + if (isset($this->issuerUniqueID)) { + $elements[] = $this->issuerUniqueID->toASN1(); } - if (count($this->_extensions) !== 0) { - $elements[] = $this->_extensions->toASN1(); + if (count($this->extensions) !== 0) { + $elements[] = $this->extensions->toASN1(); } return Sequence::create(...$elements); } @@ -345,13 +354,13 @@ public function sign( ): AttributeCertificate { $crypto ??= Crypto::getDefault(); $aci = clone $this; - if (! isset($aci->_serialNumber)) { - $aci->_serialNumber = '0'; + if (! isset($aci->serialNumber)) { + $aci->serialNumber = '0'; } - $aci->_signature = $algo; + $aci->signature = $algo; $data = $aci->toASN1() ->toDER(); $signature = $crypto->sign($data, $privkey_info, $algo); - return new AttributeCertificate($aci, $algo, $signature); + return AttributeCertificate::create($aci, $algo, $signature); } } diff --git a/src/X509/AttributeCertificate/Holder.php b/src/X509/AttributeCertificate/Holder.php index 04bd0936..d647f9ad 100644 --- a/src/X509/AttributeCertificate/Holder.php +++ b/src/X509/AttributeCertificate/Holder.php @@ -23,26 +23,25 @@ final class Holder /** * Linked object. */ - private ?ObjectDigestInfo $_objectDigestInfo = null; - - public function __construct( - /** - * Holder PKC's issuer and serial. - */ - protected ?IssuerSerial $_baseCertificateID = null, - /** - * Holder PKC's subject. - */ - protected ?GeneralNames $_entityName = null + private ?ObjectDigestInfo $objectDigestInfo = null; + + private function __construct( + private ?IssuerSerial $baseCertificateID, + private ?GeneralNames $entityName ) { } + public static function create(?IssuerSerial $baseCertificateID = null, ?GeneralNames $entityName = null): self + { + return new self($baseCertificateID, $entityName); + } + /** * Initialize from a holder's public key certificate. */ public static function fromPKC(Certificate $cert): self { - return new self(IssuerSerial::fromPKC($cert)); + return self::create(IssuerSerial::fromPKC($cert)); } /** @@ -74,9 +73,8 @@ public static function fromASN1(Sequence $seq): self ->asSequence() ); } - $obj = new self($cert_id, $entity_name); - $obj->_objectDigestInfo = $digest_info; - return $obj; + return self::create($cert_id, $entity_name) + ->withObjectDigestInfo($digest_info); } /** @@ -85,7 +83,7 @@ public static function fromASN1(Sequence $seq): self public function withBaseCertificateID(IssuerSerial $issuer): self { $obj = clone $this; - $obj->_baseCertificateID = $issuer; + $obj->baseCertificateID = $issuer; return $obj; } @@ -95,17 +93,17 @@ public function withBaseCertificateID(IssuerSerial $issuer): self public function withEntityName(GeneralNames $names): self { $obj = clone $this; - $obj->_entityName = $names; + $obj->entityName = $names; return $obj; } /** * Get self with object digest info. */ - public function withObjectDigestInfo(ObjectDigestInfo $odi): self + public function withObjectDigestInfo(?ObjectDigestInfo $odi): self { $obj = clone $this; - $obj->_objectDigestInfo = $odi; + $obj->objectDigestInfo = $odi; return $obj; } @@ -114,7 +112,7 @@ public function withObjectDigestInfo(ObjectDigestInfo $odi): self */ public function hasBaseCertificateID(): bool { - return isset($this->_baseCertificateID); + return isset($this->baseCertificateID); } /** @@ -125,7 +123,7 @@ public function baseCertificateID(): IssuerSerial if (! $this->hasBaseCertificateID()) { throw new LogicException('baseCertificateID not set.'); } - return $this->_baseCertificateID; + return $this->baseCertificateID; } /** @@ -133,7 +131,7 @@ public function baseCertificateID(): IssuerSerial */ public function hasEntityName(): bool { - return isset($this->_entityName); + return isset($this->entityName); } /** @@ -144,7 +142,7 @@ public function entityName(): GeneralNames if (! $this->hasEntityName()) { throw new LogicException('entityName not set.'); } - return $this->_entityName; + return $this->entityName; } /** @@ -152,7 +150,7 @@ public function entityName(): GeneralNames */ public function hasObjectDigestInfo(): bool { - return isset($this->_objectDigestInfo); + return isset($this->objectDigestInfo); } /** @@ -163,7 +161,7 @@ public function objectDigestInfo(): ObjectDigestInfo if (! $this->hasObjectDigestInfo()) { throw new LogicException('objectDigestInfo not set.'); } - return $this->_objectDigestInfo; + return $this->objectDigestInfo; } /** @@ -172,14 +170,14 @@ public function objectDigestInfo(): ObjectDigestInfo public function toASN1(): Sequence { $elements = []; - if (isset($this->_baseCertificateID)) { - $elements[] = ImplicitlyTaggedType::create(0, $this->_baseCertificateID->toASN1()); + if (isset($this->baseCertificateID)) { + $elements[] = ImplicitlyTaggedType::create(0, $this->baseCertificateID->toASN1()); } - if (isset($this->_entityName)) { - $elements[] = ImplicitlyTaggedType::create(1, $this->_entityName->toASN1()); + if (isset($this->entityName)) { + $elements[] = ImplicitlyTaggedType::create(1, $this->entityName->toASN1()); } - if (isset($this->_objectDigestInfo)) { - $elements[] = ImplicitlyTaggedType::create(2, $this->_objectDigestInfo->toASN1()); + if (isset($this->objectDigestInfo)) { + $elements[] = ImplicitlyTaggedType::create(2, $this->objectDigestInfo->toASN1()); } return Sequence::create(...$elements); } @@ -190,15 +188,15 @@ public function toASN1(): Sequence public function identifiesPKC(Certificate $cert): bool { // if neither baseCertificateID nor entityName are present - if ($this->_baseCertificateID === null && $this->_entityName === null) { + if ($this->baseCertificateID === null && $this->entityName === null) { return false; } // if baseCertificateID is present, but doesn't match - if ($this->_baseCertificateID !== null && ! $this->_baseCertificateID->identifiesPKC($cert)) { + if ($this->baseCertificateID !== null && ! $this->baseCertificateID->identifiesPKC($cert)) { return false; } // if entityName is present, but doesn't match - if ($this->_entityName !== null && ! $this->_checkEntityName($cert)) { + if ($this->entityName !== null && ! $this->_checkEntityName($cert)) { return false; } return true; @@ -209,7 +207,7 @@ public function identifiesPKC(Certificate $cert): bool */ private function _checkEntityName(Certificate $cert): bool { - $name = $this->_entityName?->firstDN(); + $name = $this->entityName?->firstDN(); if ($name !== null && $cert->tbsCertificate()->subject()->equals($name)) { return true; } @@ -230,7 +228,7 @@ private function _checkEntityName(Certificate $cert): bool private function _checkEntityAlternativeNames(GeneralNames $san): bool { // only directory names supported for now - $name = $this->_entityName?->firstDN(); + $name = $this->entityName?->firstDN(); if ($name === null) { return false; } diff --git a/src/X509/AttributeCertificate/IssuerSerial.php b/src/X509/AttributeCertificate/IssuerSerial.php index 00b5c7fd..d8c4af5d 100644 --- a/src/X509/AttributeCertificate/IssuerSerial.php +++ b/src/X509/AttributeCertificate/IssuerSerial.php @@ -12,7 +12,6 @@ use SpomkyLabs\Pki\X509\Certificate\UniqueIdentifier; use SpomkyLabs\Pki\X509\GeneralName\DirectoryName; use SpomkyLabs\Pki\X509\GeneralName\GeneralNames; -use function strval; /** * Implements *IssuerSerial* ASN.1 type. @@ -21,25 +20,16 @@ */ final class IssuerSerial { - /** - * Serial number as a base 10 integer. - */ - private readonly string $_serial; - - /** - * @param int|string $serial - */ - public function __construct( - /** - * Issuer name. - */ - protected GeneralNames $_issuer, - $serial, /** - * Issuer unique ID. - */ - protected ?UniqueIdentifier $_issuerUID = null + private function __construct( + private readonly GeneralNames $issuer, + private readonly string $serial, + private readonly ?UniqueIdentifier $issuerUID ) { - $this->_serial = strval($serial); + } + + public static function create(GeneralNames $issuer, string $serial, ?UniqueIdentifier $issuerUID = null): self + { + return new self($issuer, $serial, $issuerUID); } /** @@ -55,7 +45,7 @@ public static function fromASN1(Sequence $seq): self if ($seq->has(2, Element::TYPE_BIT_STRING)) { $uid = UniqueIdentifier::fromASN1($seq->at(2)->asBitString()); } - return new self($issuer, $serial, $uid); + return self::create($issuer, $serial, $uid); } /** @@ -67,7 +57,7 @@ public static function fromPKC(Certificate $cert): self $issuer = GeneralNames::create(DirectoryName::create($tbsCert->issuer())); $serial = $tbsCert->serialNumber(); $uid = $tbsCert->hasIssuerUniqueID() ? $tbsCert->issuerUniqueID() : null; - return new self($issuer, $serial, $uid); + return self::create($issuer, $serial, $uid); } /** @@ -75,7 +65,7 @@ public static function fromPKC(Certificate $cert): self */ public function issuer(): GeneralNames { - return $this->_issuer; + return $this->issuer; } /** @@ -83,7 +73,7 @@ public function issuer(): GeneralNames */ public function serial(): string { - return $this->_serial; + return $this->serial; } /** @@ -91,7 +81,7 @@ public function serial(): string */ public function hasIssuerUID(): bool { - return isset($this->_issuerUID); + return isset($this->issuerUID); } /** @@ -102,7 +92,7 @@ public function issuerUID(): UniqueIdentifier if (! $this->hasIssuerUID()) { throw new LogicException('issuerUID not set.'); } - return $this->_issuerUID; + return $this->issuerUID; } /** @@ -110,9 +100,9 @@ public function issuerUID(): UniqueIdentifier */ public function toASN1(): Sequence { - $elements = [$this->_issuer->toASN1(), Integer::create($this->_serial)]; - if (isset($this->_issuerUID)) { - $elements[] = $this->_issuerUID->toASN1(); + $elements = [$this->issuer->toASN1(), Integer::create($this->serial)]; + if (isset($this->issuerUID)) { + $elements[] = $this->issuerUID->toASN1(); } return Sequence::create(...$elements); } @@ -123,13 +113,13 @@ public function toASN1(): Sequence public function identifiesPKC(Certificate $cert): bool { $tbs = $cert->tbsCertificate(); - if (! $tbs->issuer()->equals($this->_issuer->firstDN())) { + if (! $tbs->issuer()->equals($this->issuer->firstDN())) { return false; } - if ($tbs->serialNumber() !== $this->_serial) { + if ($tbs->serialNumber() !== $this->serial) { return false; } - if ($this->_issuerUID !== null && ! $this->_checkUniqueID($cert)) { + if ($this->issuerUID !== null && ! $this->_checkUniqueID($cert)) { return false; } return true; @@ -146,6 +136,6 @@ private function _checkUniqueID(Certificate $cert): bool $uid = $cert->tbsCertificate() ->issuerUniqueID() ->string(); - return $this->_issuerUID?->string() === $uid; + return $this->issuerUID?->string() === $uid; } } diff --git a/src/X509/AttributeCertificate/ObjectDigestInfo.php b/src/X509/AttributeCertificate/ObjectDigestInfo.php index eb0ca6c2..78a52656 100644 --- a/src/X509/AttributeCertificate/ObjectDigestInfo.php +++ b/src/X509/AttributeCertificate/ObjectDigestInfo.php @@ -26,24 +26,21 @@ final class ObjectDigestInfo final public const TYPE_OTHER_OBJECT_TYPES = 2; - /** - * OID of other object type. - */ - private ?string $_otherObjectTypeID; - - public function __construct( - /** - * Object type. - */ - protected int $_digestedObjectType, /** - * Digest algorithm. - */ - protected AlgorithmIdentifierType $_digestAlgorithm, /** - * Object digest. - */ - protected BitString $_objectDigest + private function __construct( + private readonly int $digestedObjectType, + private readonly AlgorithmIdentifierType $digestAlgorithm, + private readonly BitString $objectDigest, + private readonly ?string $otherObjectTypeID ) { - $this->_otherObjectTypeID = null; + } + + public static function create( + int $digestedObjectType, + AlgorithmIdentifierType $digestAlgorithm, + BitString $objectDigest, + ?string $otherObjectTypeID = null + ): self { + return new self($digestedObjectType, $digestAlgorithm, $objectDigest, $otherObjectTypeID); } /** @@ -64,9 +61,7 @@ public static function fromASN1(Sequence $seq): self $algo = AlgorithmIdentifier::fromASN1($seq->at($idx++)->asSequence()); $digest = $seq->at($idx) ->asBitString(); - $obj = new self($type, $algo, $digest); - $obj->_otherObjectTypeID = $oid; - return $obj; + return self::create($type, $algo, $digest, $oid); } /** @@ -74,12 +69,12 @@ public static function fromASN1(Sequence $seq): self */ public function toASN1(): Sequence { - $elements = [Enumerated::create($this->_digestedObjectType)]; - if (isset($this->_otherObjectTypeID)) { - $elements[] = ObjectIdentifier::create($this->_otherObjectTypeID); + $elements = [Enumerated::create($this->digestedObjectType)]; + if (isset($this->otherObjectTypeID)) { + $elements[] = ObjectIdentifier::create($this->otherObjectTypeID); } - $elements[] = $this->_digestAlgorithm->toASN1(); - $elements[] = $this->_objectDigest; + $elements[] = $this->digestAlgorithm->toASN1(); + $elements[] = $this->objectDigest; return Sequence::create(...$elements); } } diff --git a/src/X509/AttributeCertificate/V2Form.php b/src/X509/AttributeCertificate/V2Form.php index eb9a3de1..ee5813f8 100644 --- a/src/X509/AttributeCertificate/V2Form.php +++ b/src/X509/AttributeCertificate/V2Form.php @@ -19,23 +19,19 @@ */ final class V2Form extends AttCertIssuer { - /** - * Issuer PKC's issuer and serial. - */ - protected ?IssuerSerial $_baseCertificateID; - - /** - * Linked object. - */ - protected ?ObjectDigestInfo $_objectDigestInfo; - - public function __construct(/** - * Issuer name. - */ - protected ?GeneralNames $_issuerName = null + private function __construct( + private readonly ?GeneralNames $issuerName, + private readonly ?IssuerSerial $baseCertificateID, + private readonly ?ObjectDigestInfo $objectDigestInfo ) { - $this->_baseCertificateID = null; - $this->_objectDigestInfo = null; + } + + public static function create( + ?GeneralNames $issuerName = null, + ?IssuerSerial $baseCertificateID = null, + ?ObjectDigestInfo $objectDigestInfo = null + ): self { + return new self($issuerName, $baseCertificateID, $objectDigestInfo); } /** @@ -63,10 +59,7 @@ public static function fromV2ASN1(Sequence $seq): self ->asSequence() ); } - $obj = new self($issuer); - $obj->_baseCertificateID = $cert_id; - $obj->_objectDigestInfo = $digest_info; - return $obj; + return self::create($issuer, $cert_id, $digest_info); } /** @@ -74,7 +67,7 @@ public static function fromV2ASN1(Sequence $seq): self */ public function hasIssuerName(): bool { - return isset($this->_issuerName); + return isset($this->issuerName); } /** @@ -85,7 +78,7 @@ public function issuerName(): GeneralNames if (! $this->hasIssuerName()) { throw new LogicException('issuerName not set.'); } - return $this->_issuerName; + return $this->issuerName; } /** @@ -103,21 +96,21 @@ public function name(): Name public function toASN1(): Element { $elements = []; - if (isset($this->_issuerName)) { - $elements[] = $this->_issuerName->toASN1(); + if (isset($this->issuerName)) { + $elements[] = $this->issuerName->toASN1(); } - if (isset($this->_baseCertificateID)) { - $elements[] = ImplicitlyTaggedType::create(0, $this->_baseCertificateID->toASN1()); + if (isset($this->baseCertificateID)) { + $elements[] = ImplicitlyTaggedType::create(0, $this->baseCertificateID->toASN1()); } - if (isset($this->_objectDigestInfo)) { - $elements[] = ImplicitlyTaggedType::create(1, $this->_objectDigestInfo->toASN1()); + if (isset($this->objectDigestInfo)) { + $elements[] = ImplicitlyTaggedType::create(1, $this->objectDigestInfo->toASN1()); } return ImplicitlyTaggedType::create(0, Sequence::create(...$elements)); } public function identifiesPKC(Certificate $cert): bool { - $name = $this->_issuerName?->firstDN(); + $name = $this->issuerName?->firstDN(); return ! ($name === null || ! $cert->tbsCertificate()->subject()->equals($name)); } } diff --git a/src/X509/AttributeCertificate/Validation/ACValidationConfig.php b/src/X509/AttributeCertificate/Validation/ACValidationConfig.php index 8a15b78e..4f994698 100644 --- a/src/X509/AttributeCertificate/Validation/ACValidationConfig.php +++ b/src/X509/AttributeCertificate/Validation/ACValidationConfig.php @@ -16,25 +16,30 @@ final class ACValidationConfig /** * Evaluation reference time. */ - private DateTimeImmutable $_evalTime; + private DateTimeImmutable $evalTime; /** * Permitted targets. * * @var Target[] */ - private array $_targets; + private array $targets; /** - * @param CertificationPath $_holderPath Certification path of the AC holder - * @param CertificationPath $_issuerPath Certification path of the AC issuer + * @param CertificationPath $holderPath Certification path of the AC holder + * @param CertificationPath $issuerPath Certification path of the AC issuer */ - public function __construct( - protected CertificationPath $_holderPath, - protected CertificationPath $_issuerPath + private function __construct( + private readonly CertificationPath $holderPath, + private readonly CertificationPath $issuerPath ) { - $this->_evalTime = new DateTimeImmutable(); - $this->_targets = []; + $this->evalTime = new DateTimeImmutable(); + $this->targets = []; + } + + public static function create(CertificationPath $holderPath, CertificationPath $issuerPath): self + { + return new self($holderPath, $issuerPath); } /** @@ -42,7 +47,7 @@ public function __construct( */ public function holderPath(): CertificationPath { - return $this->_holderPath; + return $this->holderPath; } /** @@ -50,7 +55,7 @@ public function holderPath(): CertificationPath */ public function issuerPath(): CertificationPath { - return $this->_issuerPath; + return $this->issuerPath; } /** @@ -59,7 +64,7 @@ public function issuerPath(): CertificationPath public function withEvaluationTime(DateTimeImmutable $dt): self { $obj = clone $this; - $obj->_evalTime = $dt; + $obj->evalTime = $dt; return $obj; } @@ -68,7 +73,7 @@ public function withEvaluationTime(DateTimeImmutable $dt): self */ public function evaluationTime(): DateTimeImmutable { - return $this->_evalTime; + return $this->evalTime; } /** @@ -77,7 +82,7 @@ public function evaluationTime(): DateTimeImmutable public function withTargets(Target ...$targets): self { $obj = clone $this; - $obj->_targets = $targets; + $obj->targets = $targets; return $obj; } @@ -88,6 +93,6 @@ public function withTargets(Target ...$targets): self */ public function targets(): array { - return $this->_targets; + return $this->targets; } } diff --git a/src/X509/AttributeCertificate/Validation/ACValidator.php b/src/X509/AttributeCertificate/Validation/ACValidator.php index 978d80d1..cdd8adf2 100644 --- a/src/X509/AttributeCertificate/Validation/ACValidator.php +++ b/src/X509/AttributeCertificate/Validation/ACValidator.php @@ -25,19 +25,27 @@ final class ACValidator /** * Crypto engine. */ - private readonly Crypto $_crypto; + private readonly Crypto $crypto; /** - * @param AttributeCertificate $_ac Attribute certificate to validate - * @param ACValidationConfig $_config Validation configuration + * @param AttributeCertificate $ac Attribute certificate to validate + * @param ACValidationConfig $config Validation configuration * @param null|Crypto $crypto Crypto engine, use default if not set */ - public function __construct( - protected AttributeCertificate $_ac, - protected ACValidationConfig $_config, - ?Crypto $crypto = null + private function __construct( + private readonly AttributeCertificate $ac, + private readonly ACValidationConfig $config, + ?Crypto $crypto ) { - $this->_crypto = $crypto ?? Crypto::getDefault(); + $this->crypto = $crypto ?? Crypto::getDefault(); + } + + public static function create( + AttributeCertificate $ac, + ACValidationConfig $config, + ?Crypto $crypto = null + ): self { + return new self($ac, $config, $crypto); } /** @@ -47,12 +55,12 @@ public function __construct( */ public function validate(): AttributeCertificate { - $this->_validateHolder(); - $issuer = $this->_verifyIssuer(); - $this->_validateIssuerProfile($issuer); - $this->_validateTime(); - $this->_validateTargeting(); - return $this->_ac; + $this->validateHolder(); + $issuer = $this->verifyIssuer(); + $this->validateIssuerProfile($issuer); + $this->validateTime(); + $this->validateTargeting(); + return $this->ac; } /** @@ -60,19 +68,19 @@ public function validate(): AttributeCertificate * * @return Certificate Certificate of the AC's holder */ - private function _validateHolder(): Certificate + private function validateHolder(): Certificate { - $path = $this->_config->holderPath(); + $path = $this->config->holderPath(); $config = PathValidationConfig::defaultConfig() ->withMaxLength(count($path)) - ->withDateTime($this->_config->evaluationTime()); + ->withDateTime($this->config->evaluationTime()); try { - $holder = $path->validate($config, $this->_crypto) + $holder = $path->validate($config, $this->crypto) ->certificate(); } catch (PathValidationException $e) { throw new ACValidationException("Failed to validate holder PKC's certification path.", 0, $e); } - if (! $this->_ac->isHeldBy($holder)) { + if (! $this->ac->isHeldBy($holder)) { throw new ACValidationException("Name mismatch of AC's holder PKC."); } return $holder; @@ -83,24 +91,24 @@ private function _validateHolder(): Certificate * * @return Certificate Certificate of the AC's issuer */ - private function _verifyIssuer(): Certificate + private function verifyIssuer(): Certificate { - $path = $this->_config->issuerPath(); + $path = $this->config->issuerPath(); $config = PathValidationConfig::defaultConfig() ->withMaxLength(count($path)) - ->withDateTime($this->_config->evaluationTime()); + ->withDateTime($this->config->evaluationTime()); try { - $issuer = $path->validate($config, $this->_crypto) + $issuer = $path->validate($config, $this->crypto) ->certificate(); } catch (PathValidationException $e) { throw new ACValidationException("Failed to validate issuer PKC's certification path.", 0, $e); } - if (! $this->_ac->isIssuedBy($issuer)) { + if (! $this->ac->isIssuedBy($issuer)) { throw new ACValidationException("Name mismatch of AC's issuer PKC."); } $pubkey_info = $issuer->tbsCertificate() ->subjectPublicKeyInfo(); - if (! $this->_ac->verify($pubkey_info, $this->_crypto)) { + if (! $this->ac->verify($pubkey_info, $this->crypto)) { throw new ACValidationException('Failed to verify signature.'); } return $issuer; @@ -111,7 +119,7 @@ private function _verifyIssuer(): Certificate * * @see https://tools.ietf.org/html/rfc5755#section-4.5 */ - private function _validateIssuerProfile(Certificate $cert): void + private function validateIssuerProfile(Certificate $cert): void { $exts = $cert->tbsCertificate() ->extensions(); @@ -129,10 +137,10 @@ private function _validateIssuerProfile(Certificate $cert): void /** * Validate AC's validity period. */ - private function _validateTime(): void + private function validateTime(): void { - $t = $this->_config->evaluationTime(); - $validity = $this->_ac->acinfo() + $t = $this->config->evaluationTime(); + $validity = $this->ac->acinfo() ->validityPeriod(); if ($validity->notBeforeTime()->diff($t)->invert === 1) { throw new ACValidationException('Validity period has not started.'); @@ -145,9 +153,9 @@ private function _validateTime(): void /** * Validate AC's target information. */ - private function _validateTargeting(): void + private function validateTargeting(): void { - $exts = $this->_ac->acinfo() + $exts = $this->ac->acinfo() ->extensions(); // if target information extension is not present if (! $exts->has(Extension::OID_TARGET_INFORMATION)) { @@ -167,7 +175,7 @@ private function _validateTargeting(): void */ private function _hasMatchingTarget(Targets $targets): bool { - foreach ($this->_config->targets() as $target) { + foreach ($this->config->targets() as $target) { if ($targets->hasTarget($target)) { return true; } diff --git a/src/X509/Certificate/Certificate.php b/src/X509/Certificate/Certificate.php index 8869cbf6..eb5a09cc 100644 --- a/src/X509/Certificate/Certificate.php +++ b/src/X509/Certificate/Certificate.php @@ -22,19 +22,15 @@ */ final class Certificate implements Stringable { - public function __construct( - /** - * "To be signed" certificate information. - */ - protected TBSCertificate $_tbsCertificate, - /** - * Signature algorithm. - */ - protected SignatureAlgorithmIdentifier $_signatureAlgorithm, - /** - * Signature value. - */ - protected Signature $_signatureValue + /** + * @param TBSCertificate $tbsCertificate "To be signed" certificate information. + * @param SignatureAlgorithmIdentifier $signatureAlgorithm Signature algorithm. + * @param Signature $signatureValue Signature value. + */ + private function __construct( + private readonly TBSCertificate $tbsCertificate, + private readonly SignatureAlgorithmIdentifier $signatureAlgorithm, + private readonly Signature $signatureValue ) { } @@ -47,6 +43,14 @@ public function __toString(): string ->string(); } + public static function create( + TBSCertificate $tbsCertificate, + SignatureAlgorithmIdentifier $signatureAlgorithm, + Signature $signatureValue + ): self { + return new self($tbsCertificate, $signatureAlgorithm, $signatureValue); + } + /** * Initialize from ASN.1. */ @@ -58,7 +62,7 @@ public static function fromASN1(Sequence $seq): self throw new UnexpectedValueException('Unsupported signature algorithm ' . $algo->oid() . '.'); } $signature = Signature::fromSignatureData($seq->at(2)->asBitString()->string(), $algo); - return new self($tbsCert, $algo, $signature); + return self::create($tbsCert, $algo, $signature); } /** @@ -85,7 +89,7 @@ public static function fromPEM(PEM $pem): self */ public function tbsCertificate(): TBSCertificate { - return $this->_tbsCertificate; + return $this->tbsCertificate; } /** @@ -93,7 +97,7 @@ public function tbsCertificate(): TBSCertificate */ public function signatureAlgorithm(): SignatureAlgorithmIdentifier { - return $this->_signatureAlgorithm; + return $this->signatureAlgorithm; } /** @@ -101,7 +105,7 @@ public function signatureAlgorithm(): SignatureAlgorithmIdentifier */ public function signatureValue(): Signature { - return $this->_signatureValue; + return $this->signatureValue; } /** @@ -109,8 +113,8 @@ public function signatureValue(): Signature */ public function isSelfIssued(): bool { - return $this->_tbsCertificate->subject() - ->equals($this->_tbsCertificate->issuer()); + return $this->tbsCertificate->subject() + ->equals($this->tbsCertificate->issuer()); } /** @@ -130,9 +134,9 @@ public function equals(self $cert): bool public function toASN1(): Sequence { return Sequence::create( - $this->_tbsCertificate->toASN1(), - $this->_signatureAlgorithm->toASN1(), - $this->_signatureValue->bitString() + $this->tbsCertificate->toASN1(), + $this->signatureAlgorithm->toASN1(), + $this->signatureValue->bitString() ); } @@ -164,9 +168,9 @@ public function toPEM(): PEM public function verify(PublicKeyInfo $pubkey_info, ?Crypto $crypto = null): bool { $crypto ??= Crypto::getDefault(); - $data = $this->_tbsCertificate->toASN1() + $data = $this->tbsCertificate->toASN1() ->toDER(); - return $crypto->verify($data, $this->_signatureValue, $pubkey_info, $this->_signatureAlgorithm); + return $crypto->verify($data, $this->signatureValue, $pubkey_info, $this->signatureAlgorithm); } /** @@ -174,8 +178,8 @@ public function verify(PublicKeyInfo $pubkey_info, ?Crypto $crypto = null): bool */ private function _hasEqualSerialNumber(self $cert): bool { - $sn1 = $this->_tbsCertificate->serialNumber(); - $sn2 = $cert->_tbsCertificate->serialNumber(); + $sn1 = $this->tbsCertificate->serialNumber(); + $sn2 = $cert->tbsCertificate->serialNumber(); return $sn1 === $sn2; } @@ -184,9 +188,9 @@ private function _hasEqualSerialNumber(self $cert): bool */ private function _hasEqualPublicKey(self $cert): bool { - $kid1 = $this->_tbsCertificate->subjectPublicKeyInfo() + $kid1 = $this->tbsCertificate->subjectPublicKeyInfo() ->keyIdentifier(); - $kid2 = $cert->_tbsCertificate->subjectPublicKeyInfo() + $kid2 = $cert->tbsCertificate->subjectPublicKeyInfo() ->keyIdentifier(); return $kid1 === $kid2; } @@ -196,8 +200,8 @@ private function _hasEqualPublicKey(self $cert): bool */ private function _hasEqualSubject(self $cert): bool { - $dn1 = $this->_tbsCertificate->subject(); - $dn2 = $cert->_tbsCertificate->subject(); + $dn1 = $this->tbsCertificate->subject(); + $dn2 = $cert->tbsCertificate->subject(); return $dn1->equals($dn2); } } diff --git a/src/X509/Certificate/CertificateBundle.php b/src/X509/Certificate/CertificateBundle.php index 25edd4c5..3f1a535b 100644 --- a/src/X509/Certificate/CertificateBundle.php +++ b/src/X509/Certificate/CertificateBundle.php @@ -21,21 +21,21 @@ final class CertificateBundle implements Countable, IteratorAggregate * * @var Certificate[] */ - private array $_certs; + private array $certs; /** * Mapping from public key id to array of certificates. * * @var null|(Certificate[])[] */ - private $_keyIdMap; + private ?array $keyIdMap = null; /** * @param Certificate ...$certs Certificate objects */ - public function __construct(Certificate ...$certs) + private function __construct(Certificate ...$certs) { - $this->_certs = $certs; + $this->certs = $certs; } /** @@ -43,7 +43,12 @@ public function __construct(Certificate ...$certs) */ public function __clone() { - $this->_keyIdMap = null; + $this->keyIdMap = null; + } + + public static function create(Certificate ...$certs): self + { + return new self(...$certs); } /** @@ -54,7 +59,7 @@ public function __clone() public static function fromPEMs(PEM ...$pems): self { $certs = array_map(static fn ($pem) => Certificate::fromPEM($pem), $pems); - return new self(...$certs); + return self::create(...$certs); } /** @@ -71,7 +76,7 @@ public static function fromPEMBundle(PEMBundle $pem_bundle): self public function withCertificates(Certificate ...$cert): self { $obj = clone $this; - $obj->_certs = array_merge($obj->_certs, $cert); + $obj->certs = array_merge($obj->certs, $cert); return $obj; } @@ -80,11 +85,11 @@ public function withCertificates(Certificate ...$cert): self */ public function withPEMBundle(PEMBundle $pem_bundle): self { - $certs = $this->_certs; + $certs = $this->certs; foreach ($pem_bundle as $pem) { $certs[] = Certificate::fromPEM($pem); } - return new self(...$certs); + return self::create(...$certs); } /** @@ -92,9 +97,9 @@ public function withPEMBundle(PEMBundle $pem_bundle): self */ public function withPEM(PEM $pem): self { - $certs = $this->_certs; + $certs = $this->certs; $certs[] = Certificate::fromPEM($pem); - return new self(...$certs); + return self::create(...$certs); } /** @@ -137,7 +142,7 @@ public function allBySubjectKeyIdentifier(string $id): array */ public function all(): array { - return $this->_certs; + return $this->certs; } /** @@ -145,7 +150,7 @@ public function all(): array */ public function count(): int { - return count($this->_certs); + return count($this->certs); } /** @@ -155,7 +160,7 @@ public function count(): int */ public function getIterator(): ArrayIterator { - return new ArrayIterator($this->_certs); + return new ArrayIterator($this->certs); } /** @@ -166,17 +171,17 @@ public function getIterator(): ArrayIterator private function _getKeyIdMap(): array { // lazily build mapping - if (! isset($this->_keyIdMap)) { - $this->_keyIdMap = []; - foreach ($this->_certs as $cert) { + if (! isset($this->keyIdMap)) { + $this->keyIdMap = []; + foreach ($this->certs as $cert) { $id = self::_getCertKeyId($cert); - if (! isset($this->_keyIdMap[$id])) { - $this->_keyIdMap[$id] = []; + if (! isset($this->keyIdMap[$id])) { + $this->keyIdMap[$id] = []; } - array_push($this->_keyIdMap[$id], $cert); + array_push($this->keyIdMap[$id], $cert); } } - return $this->_keyIdMap; + return $this->keyIdMap; } /** diff --git a/src/X509/Certificate/CertificateChain.php b/src/X509/Certificate/CertificateChain.php index 82fee989..4ad1704e 100644 --- a/src/X509/Certificate/CertificateChain.php +++ b/src/X509/Certificate/CertificateChain.php @@ -23,14 +23,19 @@ final class CertificateChain implements Countable, IteratorAggregate * * @var Certificate[] */ - private readonly array $_certs; + private readonly array $certs; /** * @param Certificate ...$certs List of certificates, end-entity first */ - public function __construct(Certificate ...$certs) + private function __construct(Certificate ...$certs) { - $this->_certs = $certs; + $this->certs = $certs; + } + + public static function create(Certificate ...$certs): self + { + return new self(...$certs); } /** @@ -39,7 +44,7 @@ public function __construct(Certificate ...$certs) public static function fromPEMs(PEM ...$pems): self { $certs = array_map(static fn (PEM $pem) => Certificate::fromPEM($pem), $pems); - return new self(...$certs); + return self::create(...$certs); } /** @@ -58,7 +63,7 @@ public static function fromPEMString(string $str): self */ public function certificates(): array { - return $this->_certs; + return $this->certs; } /** @@ -66,10 +71,10 @@ public function certificates(): array */ public function endEntityCertificate(): Certificate { - if (count($this->_certs) === 0) { + if (count($this->certs) === 0) { throw new LogicException('No certificates.'); } - return $this->_certs[0]; + return $this->certs[0]; } /** @@ -77,10 +82,10 @@ public function endEntityCertificate(): Certificate */ public function trustAnchorCertificate(): Certificate { - if (count($this->_certs) === 0) { + if (count($this->certs) === 0) { throw new LogicException('No certificates.'); } - return $this->_certs[count($this->_certs) - 1]; + return $this->certs[count($this->certs) - 1]; } /** @@ -96,7 +101,7 @@ public function certificationPath(): CertificationPath */ public function toPEMString(): string { - return implode("\n", array_map(static fn (Certificate $cert) => $cert->toPEM()->string(), $this->_certs)); + return implode("\n", array_map(static fn (Certificate $cert) => $cert->toPEM()->string(), $this->certs)); } /** @@ -104,7 +109,7 @@ public function toPEMString(): string */ public function count(): int { - return count($this->_certs); + return count($this->certs); } /** @@ -114,6 +119,6 @@ public function count(): int */ public function getIterator(): ArrayIterator { - return new ArrayIterator($this->_certs); + return new ArrayIterator($this->certs); } } diff --git a/src/X509/Certificate/Extension/AAControlsExtension.php b/src/X509/Certificate/Extension/AAControlsExtension.php index a5e90c5d..d576e4ec 100644 --- a/src/X509/Certificate/Extension/AAControlsExtension.php +++ b/src/X509/Certificate/Extension/AAControlsExtension.php @@ -21,41 +21,41 @@ final class AAControlsExtension extends Extension { /** - * @param null|string[] $_permittedAttrs - * @param null|string[] $_excludedAttrs + * @param null|string[] $permittedAttrs + * @param null|string[] $excludedAttrs */ - public function __construct( + private function __construct( bool $critical, - /** - * Path length contraint. - */ - protected ?int $_pathLenConstraint = null, - /** - * Permitted attributes. - * - * Array of OID's. - */ - protected ?array $_permittedAttrs = null, - /** - * Excluded attributes. - * - * Array of OID's. - */ - protected ?array $_excludedAttrs = null, - /** - * Whether to permit unspecified attributes. - */ - protected bool $_permitUnSpecified = true + private readonly ?int $pathLenConstraint, + private readonly ?array $permittedAttrs, + private readonly ?array $excludedAttrs, + private readonly bool $permitUnSpecified ) { parent::__construct(self::OID_AA_CONTROLS, $critical); } + /** + * @param bool $critical Path length contraint. + * @param null|string[] $permittedAttrs Permitted attributes. + * @param null|string[] $excludedAttrs Excluded attributes. + * @param bool $permitUnSpecified Whether to permit unspecified attributes. + */ + public static function create( + bool $critical, + ?int $pathLenConstraint = null, + ?array $permittedAttrs = null, + ?array $excludedAttrs = null, + bool $permitUnSpecified = true + ): self { + return new self($critical, $pathLenConstraint, $permittedAttrs, $excludedAttrs, $permitUnSpecified); + } + /** * Check whether path length constraint is present. */ public function hasPathLen(): bool { - return isset($this->_pathLenConstraint); + return isset($this->pathLenConstraint); } /** @@ -66,7 +66,7 @@ public function pathLen(): int if (! $this->hasPathLen()) { throw new LogicException('pathLen not set.'); } - return $this->_pathLenConstraint; + return $this->pathLenConstraint; } /** @@ -74,7 +74,7 @@ public function pathLen(): int */ public function hasPermittedAttrs(): bool { - return isset($this->_permittedAttrs); + return isset($this->permittedAttrs); } /** @@ -87,7 +87,7 @@ public function permittedAttrs(): array if (! $this->hasPermittedAttrs()) { throw new LogicException('permittedAttrs not set.'); } - return $this->_permittedAttrs; + return $this->permittedAttrs; } /** @@ -95,7 +95,7 @@ public function permittedAttrs(): array */ public function hasExcludedAttrs(): bool { - return isset($this->_excludedAttrs); + return isset($this->excludedAttrs); } /** @@ -108,7 +108,7 @@ public function excludedAttrs(): array if (! $this->hasExcludedAttrs()) { throw new LogicException('excludedAttrs not set.'); } - return $this->_excludedAttrs; + return $this->excludedAttrs; } /** @@ -116,10 +116,10 @@ public function excludedAttrs(): array */ public function permitUnspecified(): bool { - return $this->_permitUnSpecified; + return $this->permitUnSpecified; } - protected static function _fromDER(string $data, bool $critical): static + protected static function fromDER(string $data, bool $critical): static { $seq = UnspecifiedType::fromDER($data)->asSequence(); $path_len = null; @@ -159,24 +159,24 @@ protected static function _fromDER(string $data, bool $critical): static ->asBoolean() ->value(); } - return new self($critical, $path_len, $permitted, $excluded, $permit_unspecified); + return self::create($critical, $path_len, $permitted, $excluded, $permit_unspecified); } - protected function _valueASN1(): Element + protected function valueASN1(): Element { $elements = []; - if (isset($this->_pathLenConstraint)) { - $elements[] = Integer::create($this->_pathLenConstraint); + if (isset($this->pathLenConstraint)) { + $elements[] = Integer::create($this->pathLenConstraint); } - if (isset($this->_permittedAttrs)) { - $oids = array_map(static fn ($oid) => ObjectIdentifier::create($oid), $this->_permittedAttrs); + if (isset($this->permittedAttrs)) { + $oids = array_map(static fn ($oid) => ObjectIdentifier::create($oid), $this->permittedAttrs); $elements[] = ImplicitlyTaggedType::create(0, Sequence::create(...$oids)); } - if (isset($this->_excludedAttrs)) { - $oids = array_map(static fn ($oid) => ObjectIdentifier::create($oid), $this->_excludedAttrs); + if (isset($this->excludedAttrs)) { + $oids = array_map(static fn ($oid) => ObjectIdentifier::create($oid), $this->excludedAttrs); $elements[] = ImplicitlyTaggedType::create(1, Sequence::create(...$oids)); } - if ($this->_permitUnSpecified !== true) { + if ($this->permitUnSpecified !== true) { $elements[] = Boolean::create(false); } return Sequence::create(...$elements); diff --git a/src/X509/Certificate/Extension/AccessDescription/AccessDescription.php b/src/X509/Certificate/Extension/AccessDescription/AccessDescription.php index 44b624e8..99c01960 100644 --- a/src/X509/Certificate/Extension/AccessDescription/AccessDescription.php +++ b/src/X509/Certificate/Extension/AccessDescription/AccessDescription.php @@ -17,12 +17,12 @@ abstract class AccessDescription { /** - * @param string $_accessMethod Access method OID - * @param GeneralName $_accessLocation Access location + * @param string $accessMethod Access method OID + * @param GeneralName $accessLocation Access location */ - public function __construct( - protected string $_accessMethod, - protected GeneralName $_accessLocation + protected function __construct( + protected readonly string $accessMethod, + protected readonly GeneralName $accessLocation ) { } @@ -36,7 +36,7 @@ abstract public static function fromASN1(Sequence $seq): static; */ public function accessMethod(): string { - return $this->_accessMethod; + return $this->accessMethod; } /** @@ -44,7 +44,7 @@ public function accessMethod(): string */ public function accessLocation(): GeneralName { - return $this->_accessLocation; + return $this->accessLocation; } /** @@ -52,6 +52,6 @@ public function accessLocation(): GeneralName */ public function toASN1(): Sequence { - return Sequence::create(ObjectIdentifier::create($this->_accessMethod), $this->_accessLocation->toASN1()); + return Sequence::create(ObjectIdentifier::create($this->accessMethod), $this->accessLocation->toASN1()); } } diff --git a/src/X509/Certificate/Extension/AccessDescription/AuthorityAccessDescription.php b/src/X509/Certificate/Extension/AccessDescription/AuthorityAccessDescription.php index 0b7f0c54..ac1fa157 100644 --- a/src/X509/Certificate/Extension/AccessDescription/AuthorityAccessDescription.php +++ b/src/X509/Certificate/Extension/AccessDescription/AuthorityAccessDescription.php @@ -21,6 +21,11 @@ final class AuthorityAccessDescription extends AccessDescription final public const OID_METHOD_CA_ISSUERS = '1.3.6.1.5.5.7.48.2'; + public static function create(string $accessMethod, GeneralName $accessLocation): self + { + return new self($accessMethod, $accessLocation); + } + /** * Initialize from ASN.1. */ @@ -34,7 +39,7 @@ public static function fromASN1(Sequence $seq): static */ public function isOSCPMethod(): bool { - return $this->_accessMethod === self::OID_METHOD_OSCP; + return $this->accessMethod === self::OID_METHOD_OSCP; } /** @@ -42,6 +47,6 @@ public function isOSCPMethod(): bool */ public function isCAIssuersMethod(): bool { - return $this->_accessMethod === self::OID_METHOD_CA_ISSUERS; + return $this->accessMethod === self::OID_METHOD_CA_ISSUERS; } } diff --git a/src/X509/Certificate/Extension/AccessDescription/SubjectAccessDescription.php b/src/X509/Certificate/Extension/AccessDescription/SubjectAccessDescription.php index d09788f0..43e3767d 100644 --- a/src/X509/Certificate/Extension/AccessDescription/SubjectAccessDescription.php +++ b/src/X509/Certificate/Extension/AccessDescription/SubjectAccessDescription.php @@ -21,6 +21,11 @@ final class SubjectAccessDescription extends AccessDescription final public const OID_METHOD_CA_REPOSITORY = '1.3.6.1.5.5.7.48.5'; + public static function create(string $accessMethod, GeneralName $accessLocation): self + { + return new self($accessMethod, $accessLocation); + } + /** * Initialize from ASN.1. */ @@ -34,7 +39,7 @@ public static function fromASN1(Sequence $seq): static */ public function isTimeStampingMethod(): bool { - return $this->_accessMethod === self::OID_METHOD_TIME_STAMPING; + return $this->accessMethod === self::OID_METHOD_TIME_STAMPING; } /** @@ -42,6 +47,6 @@ public function isTimeStampingMethod(): bool */ public function isCARepositoryMethod(): bool { - return $this->_accessMethod === self::OID_METHOD_CA_REPOSITORY; + return $this->accessMethod === self::OID_METHOD_CA_REPOSITORY; } } diff --git a/src/X509/Certificate/Extension/AuthorityInformationAccessExtension.php b/src/X509/Certificate/Extension/AuthorityInformationAccessExtension.php index a9661203..7219b228 100644 --- a/src/X509/Certificate/Extension/AuthorityInformationAccessExtension.php +++ b/src/X509/Certificate/Extension/AuthorityInformationAccessExtension.php @@ -26,12 +26,17 @@ final class AuthorityInformationAccessExtension extends Extension implements Cou * * @var AuthorityAccessDescription[] */ - private readonly array $_accessDescriptions; + private readonly array $accessDescriptions; - public function __construct(bool $critical, AuthorityAccessDescription ...$access) + private function __construct(bool $critical, AuthorityAccessDescription ...$access) { parent::__construct(self::OID_AUTHORITY_INFORMATION_ACCESS, $critical); - $this->_accessDescriptions = $access; + $this->accessDescriptions = $access; + } + + public static function create(bool $critical, AuthorityAccessDescription ...$access): self + { + return new self($critical, ...$access); } /** @@ -41,7 +46,7 @@ public function __construct(bool $critical, AuthorityAccessDescription ...$acces */ public function accessDescriptions(): array { - return $this->_accessDescriptions; + return $this->accessDescriptions; } /** @@ -51,7 +56,7 @@ public function accessDescriptions(): array */ public function count(): int { - return count($this->_accessDescriptions); + return count($this->accessDescriptions); } /** @@ -62,21 +67,21 @@ public function count(): int */ public function getIterator(): ArrayIterator { - return new ArrayIterator($this->_accessDescriptions); + return new ArrayIterator($this->accessDescriptions); } - protected static function _fromDER(string $data, bool $critical): static + protected static function fromDER(string $data, bool $critical): static { $access = array_map( - fn (UnspecifiedType $el) => AuthorityAccessDescription::fromASN1($el->asSequence()), + static fn (UnspecifiedType $el) => AuthorityAccessDescription::fromASN1($el->asSequence()), UnspecifiedType::fromDER($data)->asSequence()->elements() ); - return new self($critical, ...$access); + return self::create($critical, ...$access); } - protected function _valueASN1(): Element + protected function valueASN1(): Element { - $elements = array_map(static fn (AccessDescription $access) => $access->toASN1(), $this->_accessDescriptions); + $elements = array_map(static fn (AccessDescription $access) => $access->toASN1(), $this->accessDescriptions); return Sequence::create(...$elements); } } diff --git a/src/X509/Certificate/Extension/AuthorityKeyIdentifierExtension.php b/src/X509/Certificate/Extension/AuthorityKeyIdentifierExtension.php index 69d70d31..9fa6dd6d 100644 --- a/src/X509/Certificate/Extension/AuthorityKeyIdentifierExtension.php +++ b/src/X509/Certificate/Extension/AuthorityKeyIdentifierExtension.php @@ -13,7 +13,6 @@ use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType; use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PublicKeyInfo; use SpomkyLabs\Pki\X509\GeneralName\GeneralNames; -use function strval; use UnexpectedValueException; /** @@ -23,25 +22,27 @@ */ final class AuthorityKeyIdentifierExtension extends Extension { - /** - * Issuer serial number as a base 10 integer. - */ - protected ?string $_authorityCertSerialNumber; + private function __construct( + bool $critical, + private readonly ?string $keyIdentifier, + private readonly ?GeneralNames $authorityCertIssuer, + private readonly null|string $authorityCertSerialNumber + ) { + parent::__construct(self::OID_AUTHORITY_KEY_IDENTIFIER, $critical); + } /** * @param bool $critical Conforming CA's must mark as non-critical (false) - * @param null|string $_keyIdentifier Key identifier - * @param null|GeneralNames $_authorityCertIssuer Issuer name - * @param null|int|string $serial Issuer serial number as a base 10 integer + * @param null|string $keyIdentifier Key identifier + * @param null|GeneralNames $authorityCertIssuer Issuer name */ - public function __construct( + public static function create( bool $critical, - protected ?string $_keyIdentifier, - protected ?GeneralNames $_authorityCertIssuer = null, - $serial = null - ) { - parent::__construct(self::OID_AUTHORITY_KEY_IDENTIFIER, $critical); - $this->_authorityCertSerialNumber = isset($serial) ? strval($serial) : null; + ?string $keyIdentifier, + ?GeneralNames $authorityCertIssuer = null, + null|string $authorityCertSerialNumber = null + ): self { + return new self($critical, $keyIdentifier, $authorityCertIssuer, $authorityCertSerialNumber); } /** @@ -49,7 +50,7 @@ public function __construct( */ public static function fromPublicKeyInfo(PublicKeyInfo $pki): self { - return new self(false, $pki->keyIdentifier()); + return self::create(false, $pki->keyIdentifier()); } /** @@ -57,7 +58,7 @@ public static function fromPublicKeyInfo(PublicKeyInfo $pki): self */ public function hasKeyIdentifier(): bool { - return isset($this->_keyIdentifier); + return isset($this->keyIdentifier); } /** @@ -68,7 +69,7 @@ public function keyIdentifier(): string if (! $this->hasKeyIdentifier()) { throw new LogicException('keyIdentifier not set.'); } - return $this->_keyIdentifier; + return $this->keyIdentifier; } /** @@ -76,7 +77,7 @@ public function keyIdentifier(): string */ public function hasIssuer(): bool { - return isset($this->_authorityCertIssuer); + return isset($this->authorityCertIssuer); } public function issuer(): GeneralNames @@ -84,7 +85,7 @@ public function issuer(): GeneralNames if (! $this->hasIssuer()) { throw new LogicException('authorityCertIssuer not set.'); } - return $this->_authorityCertIssuer; + return $this->authorityCertIssuer; } /** @@ -92,7 +93,7 @@ public function issuer(): GeneralNames */ public function hasSerial(): bool { - return isset($this->_authorityCertSerialNumber); + return isset($this->authorityCertSerialNumber); } /** @@ -105,10 +106,10 @@ public function serial(): string if (! $this->hasSerial()) { throw new LogicException('authorityCertSerialNumber not set.'); } - return $this->_authorityCertSerialNumber; + return $this->authorityCertSerialNumber; } - protected static function _fromDER(string $data, bool $critical): static + protected static function fromDER(string $data, bool $critical): static { $seq = UnspecifiedType::fromDER($data)->asSequence(); $keyIdentifier = null; @@ -134,28 +135,28 @@ protected static function _fromDER(string $data, bool $critical): static ->asInteger() ->number(); } - return new self($critical, $keyIdentifier, $issuer, $serial); + return self::create($critical, $keyIdentifier, $issuer, $serial); } - protected function _valueASN1(): Element + protected function valueASN1(): Element { $elements = []; - if (isset($this->_keyIdentifier)) { - $elements[] = ImplicitlyTaggedType::create(0, OctetString::create($this->_keyIdentifier)); + if (isset($this->keyIdentifier)) { + $elements[] = ImplicitlyTaggedType::create(0, OctetString::create($this->keyIdentifier)); } // if either issuer or serial is set, both must be set - if (isset($this->_authorityCertIssuer) || - isset($this->_authorityCertSerialNumber)) { - if (! isset($this->_authorityCertIssuer, - $this->_authorityCertSerialNumber)) { + if (isset($this->authorityCertIssuer) || + isset($this->authorityCertSerialNumber)) { + if (! isset($this->authorityCertIssuer, + $this->authorityCertSerialNumber)) { throw new LogicException( 'AuthorityKeyIdentifier must have both' . ' authorityCertIssuer and authorityCertSerialNumber' . ' present or both absent.' ); } - $elements[] = ImplicitlyTaggedType::create(1, $this->_authorityCertIssuer->toASN1()); - $elements[] = ImplicitlyTaggedType::create(2, Integer::create($this->_authorityCertSerialNumber)); + $elements[] = ImplicitlyTaggedType::create(1, $this->authorityCertIssuer->toASN1()); + $elements[] = ImplicitlyTaggedType::create(2, Integer::create($this->authorityCertSerialNumber)); } return Sequence::create(...$elements); } diff --git a/src/X509/Certificate/Extension/BasicConstraintsExtension.php b/src/X509/Certificate/Extension/BasicConstraintsExtension.php index ff02a16d..1253c466 100644 --- a/src/X509/Certificate/Extension/BasicConstraintsExtension.php +++ b/src/X509/Certificate/Extension/BasicConstraintsExtension.php @@ -18,24 +18,29 @@ */ final class BasicConstraintsExtension extends Extension { - public function __construct( - bool $critical, /** - * Whether certificate is a CA. - */ - protected bool $_ca, /** - * Maximum certification path length. + /** + * @param bool $ca Whether certificate is a CA. + * @param int|null $pathLen Maximum certification path length. */ - protected ?int $_pathLen = null + private function __construct( + bool $critical, + private readonly bool $ca, + private readonly ?int $pathLen ) { parent::__construct(self::OID_BASIC_CONSTRAINTS, $critical); } + public static function create(bool $critical, bool $ca, ?int $pathLen = null): self + { + return new self($critical, $ca, $pathLen); + } + /** * Whether certificate is a CA. */ public function isCA(): bool { - return $this->_ca; + return $this->ca; } /** @@ -43,7 +48,7 @@ public function isCA(): bool */ public function hasPathLen(): bool { - return isset($this->_pathLen); + return isset($this->pathLen); } /** @@ -54,10 +59,10 @@ public function pathLen(): int if (! $this->hasPathLen()) { throw new LogicException('pathLenConstraint not set.'); } - return $this->_pathLen; + return $this->pathLen; } - protected static function _fromDER(string $data, bool $critical): static + protected static function fromDER(string $data, bool $critical): static { $seq = UnspecifiedType::fromDER($data)->asSequence(); $ca = false; @@ -73,17 +78,17 @@ protected static function _fromDER(string $data, bool $critical): static ->asInteger() ->intNumber(); } - return new self($critical, $ca, $path_len); + return self::create($critical, $ca, $path_len); } - protected function _valueASN1(): Element + protected function valueASN1(): Element { $elements = []; - if ($this->_ca) { + if ($this->ca) { $elements[] = Boolean::create(true); } - if (isset($this->_pathLen)) { - $elements[] = Integer::create($this->_pathLen); + if (isset($this->pathLen)) { + $elements[] = Integer::create($this->pathLen); } return Sequence::create(...$elements); } diff --git a/src/X509/Certificate/Extension/CRLDistributionPointsExtension.php b/src/X509/Certificate/Extension/CRLDistributionPointsExtension.php index 6c60d5f1..7e50d504 100644 --- a/src/X509/Certificate/Extension/CRLDistributionPointsExtension.php +++ b/src/X509/Certificate/Extension/CRLDistributionPointsExtension.php @@ -27,12 +27,12 @@ class CRLDistributionPointsExtension extends Extension implements Countable, Ite * * @var DistributionPoint[] */ - protected array $_distributionPoints; + protected array $distributionPoints; - protected function __construct(string $oid, bool $critical, DistributionPoint ...$distribution_points) + protected function __construct(string $oid, bool $critical, DistributionPoint ...$distributionPoints) { parent::__construct($oid, $critical); - $this->_distributionPoints = $distribution_points; + $this->distributionPoints = $distributionPoints; } public static function create(bool $critical, DistributionPoint ...$distribution_points): self @@ -47,7 +47,7 @@ public static function create(bool $critical, DistributionPoint ...$distribution */ public function distributionPoints(): array { - return $this->_distributionPoints; + return $this->distributionPoints; } /** @@ -57,7 +57,7 @@ public function distributionPoints(): array */ public function count(): int { - return count($this->_distributionPoints); + return count($this->distributionPoints); } /** @@ -67,13 +67,13 @@ public function count(): int */ public function getIterator(): ArrayIterator { - return new ArrayIterator($this->_distributionPoints); + return new ArrayIterator($this->distributionPoints); } - protected static function _fromDER(string $data, bool $critical): static + protected static function fromDER(string $data, bool $critical): static { $dps = array_map( - fn (UnspecifiedType $el) => DistributionPoint::fromASN1($el->asSequence()), + static fn (UnspecifiedType $el) => DistributionPoint::fromASN1($el->asSequence()), UnspecifiedType::fromDER($data)->asSequence()->elements() ); if (count($dps) === 0) { @@ -83,12 +83,12 @@ protected static function _fromDER(string $data, bool $critical): static return static::create($critical, ...$dps); } - protected function _valueASN1(): Element + protected function valueASN1(): Element { - if (count($this->_distributionPoints) === 0) { + if (count($this->distributionPoints) === 0) { throw new LogicException('No distribution points.'); } - $elements = array_map(static fn (DistributionPoint $dp) => $dp->toASN1(), $this->_distributionPoints); + $elements = array_map(static fn (DistributionPoint $dp) => $dp->toASN1(), $this->distributionPoints); return Sequence::create(...$elements); } } diff --git a/src/X509/Certificate/Extension/CertificatePoliciesExtension.php b/src/X509/Certificate/Extension/CertificatePoliciesExtension.php index bd64d25a..e834d8c7 100644 --- a/src/X509/Certificate/Extension/CertificatePoliciesExtension.php +++ b/src/X509/Certificate/Extension/CertificatePoliciesExtension.php @@ -29,7 +29,7 @@ final class CertificatePoliciesExtension extends Extension implements Countable, */ protected array $_policies; - public function __construct(bool $critical, PolicyInformation ...$policies) + private function __construct(bool $critical, PolicyInformation ...$policies) { parent::__construct(Extension::OID_CERTIFICATE_POLICIES, $critical); $this->_policies = []; @@ -38,6 +38,11 @@ public function __construct(bool $critical, PolicyInformation ...$policies) } } + public static function create(bool $critical, PolicyInformation ...$policies): self + { + return new self($critical, ...$policies); + } + /** * Check whether policy information by OID is present. */ @@ -96,19 +101,19 @@ public function getIterator(): ArrayIterator return new ArrayIterator($this->_policies); } - protected static function _fromDER(string $data, bool $critical): static + protected static function fromDER(string $data, bool $critical): static { $policies = array_map( - fn (UnspecifiedType $el) => PolicyInformation::fromASN1($el->asSequence()), + static fn (UnspecifiedType $el) => PolicyInformation::fromASN1($el->asSequence()), UnspecifiedType::fromDER($data)->asSequence()->elements() ); if (count($policies) === 0) { throw new UnexpectedValueException('certificatePolicies must contain at least one PolicyInformation.'); } - return new self($critical, ...$policies); + return self::create($critical, ...$policies); } - protected function _valueASN1(): Element + protected function valueASN1(): Element { if (count($this->_policies) === 0) { throw new LogicException('No policies.'); diff --git a/src/X509/Certificate/Extension/CertificatePolicy/CPSQualifier.php b/src/X509/Certificate/Extension/CertificatePolicy/CPSQualifier.php index a54adf5e..3cd94dd6 100644 --- a/src/X509/Certificate/Extension/CertificatePolicy/CPSQualifier.php +++ b/src/X509/Certificate/Extension/CertificatePolicy/CPSQualifier.php @@ -15,10 +15,15 @@ */ final class CPSQualifier extends PolicyQualifierInfo { - public function __construct( - protected string $_uri + private function __construct( + private readonly string $uri ) { - $this->_oid = self::OID_CPS; + parent::__construct(self::OID_CPS); + } + + public static function create(string $uri): self + { + return new self($uri); } /** @@ -26,16 +31,16 @@ public function __construct( */ public static function fromQualifierASN1(UnspecifiedType $el): PolicyQualifierInfo { - return new self($el->asString()->string()); + return self::create($el->asString()->string()); } public function uri(): string { - return $this->_uri; + return $this->uri; } - protected function _qualifierASN1(): Element + protected function qualifierASN1(): Element { - return IA5String::create($this->_uri); + return IA5String::create($this->uri); } } diff --git a/src/X509/Certificate/Extension/CertificatePolicy/DisplayText.php b/src/X509/Certificate/Extension/CertificatePolicy/DisplayText.php index 716e8329..911a477f 100644 --- a/src/X509/Certificate/Extension/CertificatePolicy/DisplayText.php +++ b/src/X509/Certificate/Extension/CertificatePolicy/DisplayText.php @@ -20,9 +20,9 @@ */ final class DisplayText implements Stringable { - public function __construct( - protected string $_text, - protected int $_tag + private function __construct( + private readonly string $text, + private readonly int $tag ) { } @@ -31,12 +31,17 @@ public function __toString(): string return $this->string(); } + public static function create(string $text, int $tag): self + { + return new self($text, $tag); + } + /** * Initialize from ASN.1. */ public static function fromASN1(StringType $el): self { - return new self($el->string(), $el->tag()); + return self::create($el->string(), $el->tag()); } /** @@ -44,7 +49,7 @@ public static function fromASN1(StringType $el): self */ public static function fromString(string $str): self { - return new self($str, Element::TYPE_UTF8_STRING); + return self::create($str, Element::TYPE_UTF8_STRING); } /** @@ -52,7 +57,7 @@ public static function fromString(string $str): self */ public function string(): string { - return $this->_text; + return $this->text; } /** @@ -60,13 +65,13 @@ public function string(): string */ public function toASN1(): StringType { - return match ($this->_tag) { - Element::TYPE_IA5_STRING => IA5String::create($this->_text), - Element::TYPE_VISIBLE_STRING => VisibleString::create($this->_text), - Element::TYPE_BMP_STRING => BMPString::create($this->_text), - Element::TYPE_UTF8_STRING => UTF8String::create($this->_text), + return match ($this->tag) { + Element::TYPE_IA5_STRING => IA5String::create($this->text), + Element::TYPE_VISIBLE_STRING => VisibleString::create($this->text), + Element::TYPE_BMP_STRING => BMPString::create($this->text), + Element::TYPE_UTF8_STRING => UTF8String::create($this->text), default => throw new UnexpectedValueException('Type ' . Element::tagToName( - $this->_tag + $this->tag ) . ' not supported.'), }; } diff --git a/src/X509/Certificate/Extension/CertificatePolicy/NoticeReference.php b/src/X509/Certificate/Extension/CertificatePolicy/NoticeReference.php index f235e1ae..1a58962c 100644 --- a/src/X509/Certificate/Extension/CertificatePolicy/NoticeReference.php +++ b/src/X509/Certificate/Extension/CertificatePolicy/NoticeReference.php @@ -20,16 +20,18 @@ final class NoticeReference * * @var int[] */ - private readonly array $_numbers; + private readonly array $numbers; - public function __construct( - /** - * Organization. - */ - protected DisplayText $_organization, + private function __construct( + private readonly DisplayText $organization, int ...$numbers ) { - $this->_numbers = $numbers; + $this->numbers = $numbers; + } + + public static function create(DisplayText $organization, int ...$numbers): self + { + return new self($organization, ...$numbers); } /** @@ -39,13 +41,13 @@ public static function fromASN1(Sequence $seq): self { $org = DisplayText::fromASN1($seq->at(0)->asString()); $numbers = array_map( - fn (UnspecifiedType $el) => $el->asInteger() + static fn (UnspecifiedType $el) => $el->asInteger() ->intNumber(), $seq->at(1) ->asSequence() ->elements() ); - return new self($org, ...$numbers); + return self::create($org, ...$numbers); } /** @@ -53,7 +55,7 @@ public static function fromASN1(Sequence $seq): self */ public function organization(): DisplayText { - return $this->_organization; + return $this->organization; } /** @@ -63,7 +65,7 @@ public function organization(): DisplayText */ public function numbers(): array { - return $this->_numbers; + return $this->numbers; } /** @@ -71,8 +73,8 @@ public function numbers(): array */ public function toASN1(): Sequence { - $org = $this->_organization->toASN1(); - $nums = array_map(static fn ($number) => Integer::create($number), $this->_numbers); + $org = $this->organization->toASN1(); + $nums = array_map(static fn ($number) => Integer::create($number), $this->numbers); return Sequence::create($org, Sequence::create(...$nums)); } } diff --git a/src/X509/Certificate/Extension/CertificatePolicy/PolicyInformation.php b/src/X509/Certificate/Extension/CertificatePolicy/PolicyInformation.php index ca90994e..7d505687 100644 --- a/src/X509/Certificate/Extension/CertificatePolicy/PolicyInformation.php +++ b/src/X509/Certificate/Extension/CertificatePolicy/PolicyInformation.php @@ -32,21 +32,23 @@ final class PolicyInformation implements Countable, IteratorAggregate * * @var PolicyQualifierInfo[] */ - private array $_qualifiers; + private array $qualifiers; - public function __construct( - /** - * Policy identifier. - */ - protected string $_oid, + private function __construct( + private readonly string $oid, PolicyQualifierInfo ...$qualifiers ) { - $this->_qualifiers = []; - foreach ($qualifiers as $qual) { - $this->_qualifiers[$qual->oid()] = $qual; + $this->qualifiers = []; + foreach ($qualifiers as $qualifier) { + $this->qualifiers[$qualifier->oid()] = $qualifier; } } + public static function create(string $oid, PolicyQualifierInfo ...$qualifiers): self + { + return new self($oid, ...$qualifiers); + } + /** * Initialize from ASN.1. */ @@ -58,13 +60,13 @@ public static function fromASN1(Sequence $seq): self $qualifiers = []; if (count($seq) > 1) { $qualifiers = array_map( - fn (UnspecifiedType $el) => PolicyQualifierInfo::fromASN1($el->asSequence()), + static fn (UnspecifiedType $el) => PolicyQualifierInfo::fromASN1($el->asSequence()), $seq->at(1) ->asSequence() ->elements() ); } - return new self($oid, ...$qualifiers); + return self::create($oid, ...$qualifiers); } /** @@ -72,7 +74,7 @@ public static function fromASN1(Sequence $seq): self */ public function oid(): string { - return $this->_oid; + return $this->oid; } /** @@ -80,7 +82,7 @@ public function oid(): string */ public function isAnyPolicy(): bool { - return $this->_oid === self::OID_ANY_POLICY; + return $this->oid === self::OID_ANY_POLICY; } /** @@ -90,7 +92,7 @@ public function isAnyPolicy(): bool */ public function qualifiers(): array { - return array_values($this->_qualifiers); + return array_values($this->qualifiers); } /** @@ -98,7 +100,7 @@ public function qualifiers(): array */ public function has(string $oid): bool { - return isset($this->_qualifiers[$oid]); + return isset($this->qualifiers[$oid]); } /** @@ -109,7 +111,7 @@ public function get(string $oid): PolicyQualifierInfo if (! $this->has($oid)) { throw new LogicException("No {$oid} qualifier."); } - return $this->_qualifiers[$oid]; + return $this->qualifiers[$oid]; } /** @@ -155,11 +157,11 @@ public function userNoticeQualifier(): UserNoticeQualifier */ public function toASN1(): Sequence { - $elements = [ObjectIdentifier::create($this->_oid)]; - if (count($this->_qualifiers) !== 0) { + $elements = [ObjectIdentifier::create($this->oid)]; + if (count($this->qualifiers) !== 0) { $qualifiers = array_map( - fn (PolicyQualifierInfo $pqi) => $pqi->toASN1(), - array_values($this->_qualifiers) + static fn (PolicyQualifierInfo $pqi) => $pqi->toASN1(), + array_values($this->qualifiers) ); $elements[] = Sequence::create(...$qualifiers); } @@ -173,7 +175,7 @@ public function toASN1(): Sequence */ public function count(): int { - return count($this->_qualifiers); + return count($this->qualifiers); } /** @@ -183,6 +185,6 @@ public function count(): int */ public function getIterator(): ArrayIterator { - return new ArrayIterator($this->_qualifiers); + return new ArrayIterator($this->qualifiers); } } diff --git a/src/X509/Certificate/Extension/CertificatePolicy/PolicyQualifierInfo.php b/src/X509/Certificate/Extension/CertificatePolicy/PolicyQualifierInfo.php index 4fd339c6..4ad37e73 100644 --- a/src/X509/Certificate/Extension/CertificatePolicy/PolicyQualifierInfo.php +++ b/src/X509/Certificate/Extension/CertificatePolicy/PolicyQualifierInfo.php @@ -31,12 +31,9 @@ abstract class PolicyQualifierInfo */ public const OID_UNOTICE = '1.3.6.1.5.5.7.2.2'; - /** - * Qualifier identifier. - * - * @var string - */ - protected $_oid; + protected function __construct(protected string $oid) + { + } /** * Initialize from qualifier ASN.1 element. @@ -63,7 +60,7 @@ public static function fromASN1(Sequence $seq): self */ public function oid(): string { - return $this->_oid; + return $this->oid; } /** @@ -71,11 +68,11 @@ public function oid(): string */ public function toASN1(): Sequence { - return Sequence::create(ObjectIdentifier::create($this->_oid), $this->_qualifierASN1()); + return Sequence::create(ObjectIdentifier::create($this->oid), $this->qualifierASN1()); } /** * Generate ASN.1 for the 'qualifier' field. */ - abstract protected function _qualifierASN1(): Element; + abstract protected function qualifierASN1(): Element; } diff --git a/src/X509/Certificate/Extension/CertificatePolicy/UserNoticeQualifier.php b/src/X509/Certificate/Extension/CertificatePolicy/UserNoticeQualifier.php index e833c887..31240206 100644 --- a/src/X509/Certificate/Extension/CertificatePolicy/UserNoticeQualifier.php +++ b/src/X509/Certificate/Extension/CertificatePolicy/UserNoticeQualifier.php @@ -16,16 +16,16 @@ */ final class UserNoticeQualifier extends PolicyQualifierInfo { - public function __construct( - /** - * Explicit notice text. - */ - protected ?DisplayText $_text = null, /** - * Notice reference. - */ - protected ?NoticeReference $_ref = null + private function __construct( + private readonly ?DisplayText $text, + private readonly ?NoticeReference $ref ) { - $this->_oid = self::OID_UNOTICE; + parent::__construct(self::OID_UNOTICE); + } + + public static function create(?DisplayText $text = null, ?NoticeReference $ref = null): self + { + return new self($text, $ref); } /** @@ -43,7 +43,7 @@ public static function fromQualifierASN1(UnspecifiedType $el): PolicyQualifierIn if ($seq->has($idx, Element::TYPE_STRING)) { $text = DisplayText::fromASN1($seq->at($idx)->asString()); } - return new self($text, $ref); + return self::create($text, $ref); } /** @@ -51,7 +51,7 @@ public static function fromQualifierASN1(UnspecifiedType $el): PolicyQualifierIn */ public function hasExplicitText(): bool { - return isset($this->_text); + return isset($this->text); } /** @@ -62,7 +62,7 @@ public function explicitText(): DisplayText if (! $this->hasExplicitText()) { throw new LogicException('explicitText not set.'); } - return $this->_text; + return $this->text; } /** @@ -70,7 +70,7 @@ public function explicitText(): DisplayText */ public function hasNoticeRef(): bool { - return isset($this->_ref); + return isset($this->ref); } /** @@ -81,17 +81,17 @@ public function noticeRef(): NoticeReference if (! $this->hasNoticeRef()) { throw new LogicException('noticeRef not set.'); } - return $this->_ref; + return $this->ref; } - protected function _qualifierASN1(): Element + protected function qualifierASN1(): Element { $elements = []; - if (isset($this->_ref)) { - $elements[] = $this->_ref->toASN1(); + if (isset($this->ref)) { + $elements[] = $this->ref->toASN1(); } - if (isset($this->_text)) { - $elements[] = $this->_text->toASN1(); + if (isset($this->text)) { + $elements[] = $this->text->toASN1(); } return Sequence::create(...$elements); } diff --git a/src/X509/Certificate/Extension/DistributionPoint/DistributionPoint.php b/src/X509/Certificate/Extension/DistributionPoint/DistributionPoint.php index ba73f475..d9475f98 100644 --- a/src/X509/Certificate/Extension/DistributionPoint/DistributionPoint.php +++ b/src/X509/Certificate/Extension/DistributionPoint/DistributionPoint.php @@ -18,22 +18,21 @@ */ final class DistributionPoint { - public function __construct( - /** - * Distribution point name. - */ - protected ?DistributionPointName $_distributionPoint = null, - /** - * Revocation reason. - */ - protected ?ReasonFlags $_reasons = null, - /** - * CRL issuer. - */ - protected ?GeneralNames $_issuer = null + private function __construct( + private readonly ?DistributionPointName $distributionPoint, + private readonly ?ReasonFlags $reasons, + private readonly ?GeneralNames $issuer ) { } + public static function create( + ?DistributionPointName $distributionPoint = null, + ?ReasonFlags $reasons = null, + ?GeneralNames $issuer = null + ): self { + return new self($distributionPoint, $reasons, $issuer); + } + /** * Initialize from ASN.1. */ @@ -60,7 +59,7 @@ public static function fromASN1(Sequence $seq): self ->asSequence() ); } - return new self($name, $reasons, $issuer); + return self::create($name, $reasons, $issuer); } /** @@ -68,7 +67,7 @@ public static function fromASN1(Sequence $seq): self */ public function hasDistributionPointName(): bool { - return isset($this->_distributionPoint); + return isset($this->distributionPoint); } /** @@ -79,11 +78,11 @@ public function distributionPointName(): DistributionPointName if (! $this->hasDistributionPointName()) { throw new LogicException('distributionPoint not set.'); } - return $this->_distributionPoint; + return $this->distributionPoint; } /** - * Check whether distribution point name is set and it's a full name. + * Check whether distribution point name is set, and it's a full name. */ public function hasFullName(): bool { @@ -97,10 +96,10 @@ public function hasFullName(): bool */ public function fullName(): FullName { - if (! $this->hasFullName()) { + if (! $this->distributionPoint instanceof FullName || ! $this->hasFullName()) { throw new LogicException('fullName not set.'); } - return $this->_distributionPoint; + return $this->distributionPoint; } /** @@ -118,10 +117,10 @@ public function hasRelativeName(): bool */ public function relativeName(): RelativeName { - if (! $this->hasRelativeName()) { + if (! $this->distributionPoint instanceof RelativeName || ! $this->hasRelativeName()) { throw new LogicException('nameRelativeToCRLIssuer not set.'); } - return $this->_distributionPoint; + return $this->distributionPoint; } /** @@ -129,7 +128,7 @@ public function relativeName(): RelativeName */ public function hasReasons(): bool { - return isset($this->_reasons); + return isset($this->reasons); } /** @@ -140,7 +139,7 @@ public function reasons(): ReasonFlags if (! $this->hasReasons()) { throw new LogicException('reasons not set.'); } - return $this->_reasons; + return $this->reasons; } /** @@ -148,7 +147,7 @@ public function reasons(): ReasonFlags */ public function hasCRLIssuer(): bool { - return isset($this->_issuer); + return isset($this->issuer); } /** @@ -159,7 +158,7 @@ public function crlIssuer(): GeneralNames if (! $this->hasCRLIssuer()) { throw new LogicException('crlIssuer not set.'); } - return $this->_issuer; + return $this->issuer; } /** @@ -168,14 +167,14 @@ public function crlIssuer(): GeneralNames public function toASN1(): Sequence { $elements = []; - if (isset($this->_distributionPoint)) { - $elements[] = ExplicitlyTaggedType::create(0, $this->_distributionPoint->toASN1()); + if (isset($this->distributionPoint)) { + $elements[] = ExplicitlyTaggedType::create(0, $this->distributionPoint->toASN1()); } - if (isset($this->_reasons)) { - $elements[] = ImplicitlyTaggedType::create(1, $this->_reasons->toASN1()); + if (isset($this->reasons)) { + $elements[] = ImplicitlyTaggedType::create(1, $this->reasons->toASN1()); } - if (isset($this->_issuer)) { - $elements[] = ImplicitlyTaggedType::create(2, $this->_issuer->toASN1()); + if (isset($this->issuer)) { + $elements[] = ImplicitlyTaggedType::create(2, $this->issuer->toASN1()); } return Sequence::create(...$elements); } diff --git a/src/X509/Certificate/Extension/DistributionPoint/DistributionPointName.php b/src/X509/Certificate/Extension/DistributionPoint/DistributionPointName.php index 3e0661e3..4dcce51e 100644 --- a/src/X509/Certificate/Extension/DistributionPoint/DistributionPointName.php +++ b/src/X509/Certificate/Extension/DistributionPoint/DistributionPointName.php @@ -22,12 +22,9 @@ abstract class DistributionPointName public const TAG_RDN = 1; - /** - * Type. - * - * @var int - */ - protected $_tag; + protected function __construct(protected int $tag) + { + } /** * Initialize from TaggedType. @@ -35,10 +32,10 @@ abstract class DistributionPointName public static function fromTaggedType(TaggedType $el): self { return match ($el->tag()) { - self::TAG_FULL_NAME => new FullName(GeneralNames::fromASN1( + self::TAG_FULL_NAME => FullName::create(GeneralNames::fromASN1( $el->asImplicit(Element::TYPE_SEQUENCE)->asSequence() )), - self::TAG_RDN => new RelativeName(RDN::fromASN1($el->asImplicit(Element::TYPE_SET)->asSet())), + self::TAG_RDN => RelativeName::create(RDN::fromASN1($el->asImplicit(Element::TYPE_SET)->asSet())), default => throw new UnexpectedValueException( 'DistributionPointName tag ' . $el->tag() . ' not supported.' ), @@ -50,7 +47,7 @@ public static function fromTaggedType(TaggedType $el): self */ public function tag(): int { - return $this->_tag; + return $this->tag; } /** @@ -58,7 +55,7 @@ public function tag(): int */ public function toASN1(): ImplicitlyTaggedType { - return ImplicitlyTaggedType::create($this->_tag, $this->_valueASN1()); + return ImplicitlyTaggedType::create($this->tag, $this->_valueASN1()); } /** diff --git a/src/X509/Certificate/Extension/DistributionPoint/FullName.php b/src/X509/Certificate/Extension/DistributionPoint/FullName.php index 7aa81bd6..a315737c 100644 --- a/src/X509/Certificate/Extension/DistributionPoint/FullName.php +++ b/src/X509/Certificate/Extension/DistributionPoint/FullName.php @@ -16,12 +16,15 @@ */ final class FullName extends DistributionPointName { - public function __construct(/** - * Names. - */ - protected GeneralNames $_names + private function __construct( + private readonly GeneralNames $names ) { - $this->_tag = self::TAG_FULL_NAME; + parent::__construct(self::TAG_FULL_NAME); + } + + public static function create(GeneralNames $names): self + { + return new self($names); } /** @@ -29,16 +32,16 @@ public function __construct(/** */ public static function fromURI(string $uri): self { - return new self(GeneralNames::create(UniformResourceIdentifier::create($uri))); + return self::create(GeneralNames::create(UniformResourceIdentifier::create($uri))); } public function names(): GeneralNames { - return $this->_names; + return $this->names; } protected function _valueASN1(): Element { - return $this->_names->toASN1(); + return $this->names->toASN1(); } } diff --git a/src/X509/Certificate/Extension/DistributionPoint/ReasonFlags.php b/src/X509/Certificate/Extension/DistributionPoint/ReasonFlags.php index 4accd7a1..970b61c6 100644 --- a/src/X509/Certificate/Extension/DistributionPoint/ReasonFlags.php +++ b/src/X509/Certificate/Extension/DistributionPoint/ReasonFlags.php @@ -31,20 +31,22 @@ final class ReasonFlags final public const AA_COMPROMISE = 0x001; - public function __construct( - /** - * Flags. - */ - protected int $_flags + private function __construct( + private readonly int $flags ) { } + public static function create(int $flags): self + { + return new self($flags); + } + /** * Initialize from ASN.1. */ public static function fromASN1(BitString $bs): self { - return new self(Flags::fromBitString($bs, 9)->intNumber()); + return self::create(Flags::fromBitString($bs, 9)->intNumber()); } /** @@ -52,7 +54,7 @@ public static function fromASN1(BitString $bs): self */ public function isKeyCompromise(): bool { - return $this->_flagSet(self::KEY_COMPROMISE); + return $this->flagSet(self::KEY_COMPROMISE); } /** @@ -60,7 +62,7 @@ public function isKeyCompromise(): bool */ public function isCACompromise(): bool { - return $this->_flagSet(self::CA_COMPROMISE); + return $this->flagSet(self::CA_COMPROMISE); } /** @@ -68,7 +70,7 @@ public function isCACompromise(): bool */ public function isAffiliationChanged(): bool { - return $this->_flagSet(self::AFFILIATION_CHANGED); + return $this->flagSet(self::AFFILIATION_CHANGED); } /** @@ -76,7 +78,7 @@ public function isAffiliationChanged(): bool */ public function isSuperseded(): bool { - return $this->_flagSet(self::SUPERSEDED); + return $this->flagSet(self::SUPERSEDED); } /** @@ -84,7 +86,7 @@ public function isSuperseded(): bool */ public function isCessationOfOperation(): bool { - return $this->_flagSet(self::CESSATION_OF_OPERATION); + return $this->flagSet(self::CESSATION_OF_OPERATION); } /** @@ -92,7 +94,7 @@ public function isCessationOfOperation(): bool */ public function isCertificateHold(): bool { - return $this->_flagSet(self::CERTIFICATE_HOLD); + return $this->flagSet(self::CERTIFICATE_HOLD); } /** @@ -100,7 +102,7 @@ public function isCertificateHold(): bool */ public function isPrivilegeWithdrawn(): bool { - return $this->_flagSet(self::PRIVILEGE_WITHDRAWN); + return $this->flagSet(self::PRIVILEGE_WITHDRAWN); } /** @@ -108,7 +110,7 @@ public function isPrivilegeWithdrawn(): bool */ public function isAACompromise(): bool { - return $this->_flagSet(self::AA_COMPROMISE); + return $this->flagSet(self::AA_COMPROMISE); } /** @@ -116,7 +118,7 @@ public function isAACompromise(): bool */ public function toASN1(): BitString { - $flags = Flags::create($this->_flags, 9); + $flags = Flags::create($this->flags, 9); return $flags->bitString() ->withoutTrailingZeroes(); } @@ -124,8 +126,8 @@ public function toASN1(): BitString /** * Check whether given flag is set. */ - private function _flagSet(int $flag): bool + private function flagSet(int $flag): bool { - return (bool) ($this->_flags & $flag); + return (bool) ($this->flags & $flag); } } diff --git a/src/X509/Certificate/Extension/DistributionPoint/RelativeName.php b/src/X509/Certificate/Extension/DistributionPoint/RelativeName.php index 17628a76..5f0abe67 100644 --- a/src/X509/Certificate/Extension/DistributionPoint/RelativeName.php +++ b/src/X509/Certificate/Extension/DistributionPoint/RelativeName.php @@ -15,21 +15,24 @@ */ final class RelativeName extends DistributionPointName { - public function __construct(/** - * Relative distinguished name. - */ - protected RDN $_rdn + private function __construct( + private readonly RDN $rdn ) { - $this->_tag = self::TAG_RDN; + parent::__construct(self::TAG_RDN); + } + + public static function create(RDN $rdn): self + { + return new self($rdn); } public function rdn(): RDN { - return $this->_rdn; + return $this->rdn; } protected function _valueASN1(): Element { - return $this->_rdn->toASN1(); + return $this->rdn->toASN1(); } } diff --git a/src/X509/Certificate/Extension/ExtendedKeyUsageExtension.php b/src/X509/Certificate/Extension/ExtendedKeyUsageExtension.php index 90c16a6a..bfa39b55 100644 --- a/src/X509/Certificate/Extension/ExtendedKeyUsageExtension.php +++ b/src/X509/Certificate/Extension/ExtendedKeyUsageExtension.php @@ -84,12 +84,17 @@ final class ExtendedKeyUsageExtension extends Extension implements Countable, It * * @var string[] */ - protected array $_purposes; + private readonly array $purposes; - public function __construct(bool $critical, string ...$purposes) + private function __construct(bool $critical, string ...$purposes) { parent::__construct(self::OID_EXT_KEY_USAGE, $critical); - $this->_purposes = $purposes; + $this->purposes = $purposes; + } + + public static function create(bool $critical, string ...$purposes): self + { + return new self($critical, ...$purposes); } /** @@ -100,7 +105,7 @@ public function __construct(bool $critical, string ...$purposes) public function has(string ...$oids): bool { foreach ($oids as $oid) { - if (! in_array($oid, $this->_purposes, true)) { + if (! in_array($oid, $this->purposes, true)) { return false; } } @@ -114,7 +119,7 @@ public function has(string ...$oids): bool */ public function purposes(): array { - return $this->_purposes; + return $this->purposes; } /** @@ -124,7 +129,7 @@ public function purposes(): array */ public function count(): int { - return count($this->_purposes); + return count($this->purposes); } /** @@ -134,22 +139,22 @@ public function count(): int */ public function getIterator(): ArrayIterator { - return new ArrayIterator($this->_purposes); + return new ArrayIterator($this->purposes); } - protected static function _fromDER(string $data, bool $critical): static + protected static function fromDER(string $data, bool $critical): static { $purposes = array_map( - fn (UnspecifiedType $el) => $el->asObjectIdentifier() + static fn (UnspecifiedType $el) => $el->asObjectIdentifier() ->oid(), UnspecifiedType::fromDER($data)->asSequence()->elements() ); - return new self($critical, ...$purposes); + return self::create($critical, ...$purposes); } - protected function _valueASN1(): Element + protected function valueASN1(): Element { - $elements = array_map(static fn ($oid) => ObjectIdentifier::create($oid), $this->_purposes); + $elements = array_map(static fn ($oid) => ObjectIdentifier::create($oid), $this->purposes); return Sequence::create(...$elements); } } diff --git a/src/X509/Certificate/Extension/Extension.php b/src/X509/Certificate/Extension/Extension.php index 9fcaa90f..a6ad47dc 100644 --- a/src/X509/Certificate/Extension/Extension.php +++ b/src/X509/Certificate/Extension/Extension.php @@ -225,12 +225,12 @@ abstract class Extension implements Stringable ]; /** - * @param string $_oid Extension OID - * @param bool $_critical Whether extension is critical + * @param string $oid Extension OID + * @param bool $critical Whether extension is critical */ - public function __construct( - protected string $_oid, - protected bool $_critical + protected function __construct( + private readonly string $oid, + private readonly bool $critical ) { } @@ -259,7 +259,7 @@ public static function fromASN1(Sequence $seq): self ->string(); if (array_key_exists($extnID, self::MAP_OID_TO_CLASS)) { $cls = self::MAP_OID_TO_CLASS[$extnID]; - return $cls::_fromDER($data, $critical); + return $cls::fromDER($data, $critical); } return UnknownExtension::fromRawString($extnID, $critical, $data); } @@ -269,7 +269,7 @@ public static function fromASN1(Sequence $seq): self */ public function oid(): string { - return $this->_oid; + return $this->oid; } /** @@ -277,7 +277,7 @@ public function oid(): string */ public function isCritical(): bool { - return $this->_critical; + return $this->critical; } /** @@ -285,11 +285,11 @@ public function isCritical(): bool */ public function toASN1(): Sequence { - $elements = [ObjectIdentifier::create($this->_oid)]; - if ($this->_critical) { + $elements = [ObjectIdentifier::create($this->oid)]; + if ($this->critical) { $elements[] = Boolean::create(true); } - $elements[] = $this->_extnValue(); + $elements[] = $this->extnValue(); return Sequence::create(...$elements); } @@ -298,8 +298,8 @@ public function toASN1(): Sequence */ public function extensionName(): string { - if (array_key_exists($this->_oid, self::MAP_OID_TO_NAME)) { - return self::MAP_OID_TO_NAME[$this->_oid]; + if (array_key_exists($this->oid, self::MAP_OID_TO_NAME)) { + return self::MAP_OID_TO_NAME[$this->oid]; } return $this->oid(); } @@ -307,7 +307,7 @@ public function extensionName(): string /** * Get ASN.1 structure of the extension value. */ - abstract protected function _valueASN1(): Element; + abstract protected function valueASN1(): Element; /** * Parse extension value from DER. @@ -315,13 +315,13 @@ abstract protected function _valueASN1(): Element; * @param string $data DER data * @param bool $critical Whether extension is critical */ - abstract protected static function _fromDER(string $data, bool $critical): static; + abstract protected static function fromDER(string $data, bool $critical): static; /** * Get the extnValue element. */ - protected function _extnValue(): OctetString + protected function extnValue(): OctetString { - return OctetString::create($this->_valueASN1()->toDER()); + return OctetString::create($this->valueASN1()->toDER()); } } diff --git a/src/X509/Certificate/Extension/InhibitAnyPolicyExtension.php b/src/X509/Certificate/Extension/InhibitAnyPolicyExtension.php index ae4cfc50..c4a646de 100644 --- a/src/X509/Certificate/Extension/InhibitAnyPolicyExtension.php +++ b/src/X509/Certificate/Extension/InhibitAnyPolicyExtension.php @@ -15,25 +15,30 @@ */ final class InhibitAnyPolicyExtension extends Extension { - public function __construct( + private function __construct( bool $critical, - protected int $_skipCerts + private readonly int $skipCerts ) { parent::__construct(self::OID_INHIBIT_ANY_POLICY, $critical); } + public static function create(bool $critical, int $skipCerts): self + { + return new self($critical, $skipCerts); + } + public function skipCerts(): int { - return $this->_skipCerts; + return $this->skipCerts; } - protected static function _fromDER(string $data, bool $critical): static + protected static function fromDER(string $data, bool $critical): static { - return new self($critical, UnspecifiedType::fromDER($data)->asInteger()->intNumber()); + return self::create($critical, UnspecifiedType::fromDER($data)->asInteger()->intNumber()); } - protected function _valueASN1(): Element + protected function valueASN1(): Element { - return Integer::create($this->_skipCerts); + return Integer::create($this->skipCerts); } } diff --git a/src/X509/Certificate/Extension/IssuerAlternativeNameExtension.php b/src/X509/Certificate/Extension/IssuerAlternativeNameExtension.php index 1fa60d03..57478403 100644 --- a/src/X509/Certificate/Extension/IssuerAlternativeNameExtension.php +++ b/src/X509/Certificate/Extension/IssuerAlternativeNameExtension.php @@ -15,27 +15,30 @@ */ final class IssuerAlternativeNameExtension extends Extension { - public function __construct( - bool $critical, /** - * Names. - */ - protected GeneralNames $_names + private function __construct( + bool $critical, + private readonly GeneralNames $names ) { parent::__construct(self::OID_ISSUER_ALT_NAME, $critical); } + public static function create(bool $critical, GeneralNames $names): self + { + return new self($critical, $names); + } + public function names(): GeneralNames { - return $this->_names; + return $this->names; } - protected static function _fromDER(string $data, bool $critical): static + protected static function fromDER(string $data, bool $critical): static { - return new self($critical, GeneralNames::fromASN1(UnspecifiedType::fromDER($data)->asSequence())); + return self::create($critical, GeneralNames::fromASN1(UnspecifiedType::fromDER($data)->asSequence())); } - protected function _valueASN1(): Element + protected function valueASN1(): Element { - return $this->_names->toASN1(); + return $this->names->toASN1(); } } diff --git a/src/X509/Certificate/Extension/KeyUsageExtension.php b/src/X509/Certificate/Extension/KeyUsageExtension.php index 9251def0..d6b0356b 100644 --- a/src/X509/Certificate/Extension/KeyUsageExtension.php +++ b/src/X509/Certificate/Extension/KeyUsageExtension.php @@ -33,15 +33,18 @@ final class KeyUsageExtension extends Extension final public const DECIPHER_ONLY = 0x001; - public function __construct( - bool $critical, /** - * Key usage flags. - */ - protected int $_keyUsage + private function __construct( + bool $critical, + private readonly int $keyUsage ) { parent::__construct(self::OID_KEY_USAGE, $critical); } + public static function create(bool $critical, int $keyUsage): self + { + return new self($critical, $keyUsage); + } + /** * Check whether digitalSignature flag is set. */ @@ -119,20 +122,20 @@ public function isDecipherOnly(): bool */ protected function _flagSet(int $flag): bool { - return (bool) ($this->_keyUsage & $flag); + return (bool) ($this->keyUsage & $flag); } - protected static function _fromDER(string $data, bool $critical): static + protected static function fromDER(string $data, bool $critical): static { - return new self( + return self::create( $critical, Flags::fromBitString(UnspecifiedType::fromDER($data)->asBitString(), 9)->intNumber() ); } - protected function _valueASN1(): Element + protected function valueASN1(): Element { - $flags = Flags::create($this->_keyUsage, 9); + $flags = Flags::create($this->keyUsage, 9); return $flags->bitString() ->withoutTrailingZeroes(); } diff --git a/src/X509/Certificate/Extension/NameConstraints/GeneralSubtree.php b/src/X509/Certificate/Extension/NameConstraints/GeneralSubtree.php index 0f50e2b2..bc55ca40 100644 --- a/src/X509/Certificate/Extension/NameConstraints/GeneralSubtree.php +++ b/src/X509/Certificate/Extension/NameConstraints/GeneralSubtree.php @@ -18,22 +18,33 @@ */ final class GeneralSubtree { - public function __construct( - /** - * Constraint. - */ - protected GeneralName $_base, - /** - * Not used, must be zero. - */ - protected int $_min = 0, - /** - * Not used, must be null. - */ - protected ?int $_max = null + private function __construct( + private readonly GeneralName $base, + private readonly int $min, + private readonly ?int $max ) { } + public static function create(GeneralName $base, int $min = 0, ?int $max = null): self + { + return new self($base, $min, $max); + } + + public function getBase(): GeneralName + { + return $this->base; + } + + public function getMin(): int + { + return $this->min; + } + + public function getMax(): ?int + { + return $this->max; + } + /** * Initialize from ASN.1. */ @@ -62,12 +73,12 @@ public static function fromASN1(Sequence $seq): self break; } } - return new self($base, $min, $max); + return self::create($base, $min, $max); } public function base(): GeneralName { - return $this->_base; + return $this->base; } /** @@ -75,12 +86,12 @@ public function base(): GeneralName */ public function toASN1(): Sequence { - $elements = [$this->_base->toASN1()]; - if (isset($this->_min) && $this->_min !== 0) { - $elements[] = ImplicitlyTaggedType::create(0, Integer::create($this->_min)); + $elements = [$this->base->toASN1()]; + if (isset($this->min) && $this->min !== 0) { + $elements[] = ImplicitlyTaggedType::create(0, Integer::create($this->min)); } - if (isset($this->_max)) { - $elements[] = ImplicitlyTaggedType::create(1, Integer::create($this->_max)); + if (isset($this->max)) { + $elements[] = ImplicitlyTaggedType::create(1, Integer::create($this->max)); } return Sequence::create(...$elements); } diff --git a/src/X509/Certificate/Extension/NameConstraints/GeneralSubtrees.php b/src/X509/Certificate/Extension/NameConstraints/GeneralSubtrees.php index b5f5372a..f4f5b63d 100644 --- a/src/X509/Certificate/Extension/NameConstraints/GeneralSubtrees.php +++ b/src/X509/Certificate/Extension/NameConstraints/GeneralSubtrees.php @@ -25,11 +25,16 @@ final class GeneralSubtrees implements Countable, IteratorAggregate * * @var GeneralSubtree[] */ - private readonly array $_subtrees; + private readonly array $subtrees; - public function __construct(GeneralSubtree ...$subtrees) + private function __construct(GeneralSubtree ...$subtrees) { - $this->_subtrees = $subtrees; + $this->subtrees = $subtrees; + } + + public static function create(GeneralSubtree ...$subtrees): self + { + return new self(...$subtrees); } /** @@ -38,13 +43,13 @@ public function __construct(GeneralSubtree ...$subtrees) public static function fromASN1(Sequence $seq): self { $subtrees = array_map( - fn (UnspecifiedType $el) => GeneralSubtree::fromASN1($el->asSequence()), + static fn (UnspecifiedType $el) => GeneralSubtree::fromASN1($el->asSequence()), $seq->elements() ); if (count($subtrees) === 0) { throw new UnexpectedValueException('GeneralSubtrees must contain at least one GeneralSubtree.'); } - return new self(...$subtrees); + return self::create(...$subtrees); } /** @@ -54,7 +59,7 @@ public static function fromASN1(Sequence $seq): self */ public function all(): array { - return $this->_subtrees; + return $this->subtrees; } /** @@ -62,10 +67,10 @@ public function all(): array */ public function toASN1(): Sequence { - if (count($this->_subtrees) === 0) { + if (count($this->subtrees) === 0) { throw new LogicException('No subtrees.'); } - $elements = array_map(static fn (GeneralSubtree $gs) => $gs->toASN1(), $this->_subtrees); + $elements = array_map(static fn (GeneralSubtree $gs) => $gs->toASN1(), $this->subtrees); return Sequence::create(...$elements); } @@ -74,7 +79,7 @@ public function toASN1(): Sequence */ public function count(): int { - return count($this->_subtrees); + return count($this->subtrees); } /** @@ -84,6 +89,6 @@ public function count(): int */ public function getIterator(): ArrayIterator { - return new ArrayIterator($this->_subtrees); + return new ArrayIterator($this->subtrees); } } diff --git a/src/X509/Certificate/Extension/NameConstraintsExtension.php b/src/X509/Certificate/Extension/NameConstraintsExtension.php index 12380a83..279a4012 100644 --- a/src/X509/Certificate/Extension/NameConstraintsExtension.php +++ b/src/X509/Certificate/Extension/NameConstraintsExtension.php @@ -18,24 +18,28 @@ */ final class NameConstraintsExtension extends Extension { - /** - * @param GeneralSubtrees $_permitted - * @param GeneralSubtrees $_excluded - */ - public function __construct( + private function __construct( bool $critical, - protected ?GeneralSubtrees $_permitted = null, - protected ?GeneralSubtrees $_excluded = null + private readonly ?GeneralSubtrees $permitted, + private readonly ?GeneralSubtrees $excluded ) { parent::__construct(self::OID_NAME_CONSTRAINTS, $critical); } + public static function create( + bool $critical, + ?GeneralSubtrees $permitted = null, + ?GeneralSubtrees $excluded = null + ): self { + return new self($critical, $permitted, $excluded); + } + /** * Whether permitted subtrees are present. */ public function hasPermittedSubtrees(): bool { - return isset($this->_permitted); + return isset($this->permitted); } /** @@ -46,7 +50,7 @@ public function permittedSubtrees(): GeneralSubtrees if (! $this->hasPermittedSubtrees()) { throw new LogicException('No permitted subtrees.'); } - return $this->_permitted; + return $this->permitted; } /** @@ -54,7 +58,7 @@ public function permittedSubtrees(): GeneralSubtrees */ public function hasExcludedSubtrees(): bool { - return isset($this->_excluded); + return isset($this->excluded); } /** @@ -65,10 +69,10 @@ public function excludedSubtrees(): GeneralSubtrees if (! $this->hasExcludedSubtrees()) { throw new LogicException('No excluded subtrees.'); } - return $this->_excluded; + return $this->excluded; } - protected static function _fromDER(string $data, bool $critical): static + protected static function fromDER(string $data, bool $critical): static { $seq = UnspecifiedType::fromDER($data)->asSequence(); $permitted = null; @@ -85,17 +89,17 @@ protected static function _fromDER(string $data, bool $critical): static ->asImplicit(Element::TYPE_SEQUENCE)->asSequence() ); } - return new self($critical, $permitted, $excluded); + return self::create($critical, $permitted, $excluded); } - protected function _valueASN1(): Element + protected function valueASN1(): Element { $elements = []; - if (isset($this->_permitted)) { - $elements[] = ImplicitlyTaggedType::create(0, $this->_permitted->toASN1()); + if (isset($this->permitted)) { + $elements[] = ImplicitlyTaggedType::create(0, $this->permitted->toASN1()); } - if (isset($this->_excluded)) { - $elements[] = ImplicitlyTaggedType::create(1, $this->_excluded->toASN1()); + if (isset($this->excluded)) { + $elements[] = ImplicitlyTaggedType::create(1, $this->excluded->toASN1()); } return Sequence::create(...$elements); } diff --git a/src/X509/Certificate/Extension/NoRevocationAvailableExtension.php b/src/X509/Certificate/Extension/NoRevocationAvailableExtension.php index 7f7d974e..aa3d0ad5 100644 --- a/src/X509/Certificate/Extension/NoRevocationAvailableExtension.php +++ b/src/X509/Certificate/Extension/NoRevocationAvailableExtension.php @@ -14,18 +14,23 @@ */ final class NoRevocationAvailableExtension extends Extension { - public function __construct(bool $critical) + private function __construct(bool $critical) { parent::__construct(self::OID_NO_REV_AVAIL, $critical); } - protected static function _fromDER(string $data, bool $critical): static + public static function create(bool $critical): self { - NullType::fromDER($data); return new self($critical); } - protected function _valueASN1(): Element + protected static function fromDER(string $data, bool $critical): static + { + NullType::fromDER($data); + return self::create($critical); + } + + protected function valueASN1(): Element { return NullType::create(); } diff --git a/src/X509/Certificate/Extension/PolicyConstraintsExtension.php b/src/X509/Certificate/Extension/PolicyConstraintsExtension.php index ce4053f3..5dee9547 100644 --- a/src/X509/Certificate/Extension/PolicyConstraintsExtension.php +++ b/src/X509/Certificate/Extension/PolicyConstraintsExtension.php @@ -18,20 +18,28 @@ */ final class PolicyConstraintsExtension extends Extension { - public function __construct( + private function __construct( bool $critical, - protected ?int $_requireExplicitPolicy = null, - protected ?int $_inhibitPolicyMapping = null + private readonly ?int $requireExplicitPolicy, + private readonly ?int $inhibitPolicyMapping ) { parent::__construct(self::OID_POLICY_CONSTRAINTS, $critical); } + public static function create( + bool $critical, + ?int $requireExplicitPolicy = null, + ?int $inhibitPolicyMapping = null + ): self { + return new self($critical, $requireExplicitPolicy, $inhibitPolicyMapping); + } + /** * Whether requireExplicitPolicy is present. */ public function hasRequireExplicitPolicy(): bool { - return isset($this->_requireExplicitPolicy); + return isset($this->requireExplicitPolicy); } public function requireExplicitPolicy(): int @@ -39,7 +47,7 @@ public function requireExplicitPolicy(): int if (! $this->hasRequireExplicitPolicy()) { throw new LogicException('requireExplicitPolicy not set.'); } - return $this->_requireExplicitPolicy; + return $this->requireExplicitPolicy; } /** @@ -47,7 +55,7 @@ public function requireExplicitPolicy(): int */ public function hasInhibitPolicyMapping(): bool { - return isset($this->_inhibitPolicyMapping); + return isset($this->inhibitPolicyMapping); } public function inhibitPolicyMapping(): int @@ -55,10 +63,10 @@ public function inhibitPolicyMapping(): int if (! $this->hasInhibitPolicyMapping()) { throw new LogicException('inhibitPolicyMapping not set.'); } - return $this->_inhibitPolicyMapping; + return $this->inhibitPolicyMapping; } - protected static function _fromDER(string $data, bool $critical): static + protected static function fromDER(string $data, bool $critical): static { $seq = UnspecifiedType::fromDER($data)->asSequence(); $require_explicit_policy = null; @@ -71,17 +79,17 @@ protected static function _fromDER(string $data, bool $critical): static $inhibit_policy_mapping = $seq->getTagged(1) ->asImplicit(Element::TYPE_INTEGER)->asInteger()->intNumber(); } - return new self($critical, $require_explicit_policy, $inhibit_policy_mapping); + return self::create($critical, $require_explicit_policy, $inhibit_policy_mapping); } - protected function _valueASN1(): Element + protected function valueASN1(): Element { $elements = []; - if (isset($this->_requireExplicitPolicy)) { - $elements[] = ImplicitlyTaggedType::create(0, Integer::create($this->_requireExplicitPolicy)); + if (isset($this->requireExplicitPolicy)) { + $elements[] = ImplicitlyTaggedType::create(0, Integer::create($this->requireExplicitPolicy)); } - if (isset($this->_inhibitPolicyMapping)) { - $elements[] = ImplicitlyTaggedType::create(1, Integer::create($this->_inhibitPolicyMapping)); + if (isset($this->inhibitPolicyMapping)) { + $elements[] = ImplicitlyTaggedType::create(1, Integer::create($this->inhibitPolicyMapping)); } return Sequence::create(...$elements); } diff --git a/src/X509/Certificate/Extension/PolicyMappings/PolicyMapping.php b/src/X509/Certificate/Extension/PolicyMappings/PolicyMapping.php index 8975ba5d..71750399 100644 --- a/src/X509/Certificate/Extension/PolicyMappings/PolicyMapping.php +++ b/src/X509/Certificate/Extension/PolicyMappings/PolicyMapping.php @@ -15,15 +15,20 @@ final class PolicyMapping { /** - * @param string $_issuerDomainPolicy OID of the issuer policy - * @param string $_subjectDomainPolicy OID of the subject policy + * @param string $issuerDomainPolicy OID of the issuer policy + * @param string $subjectDomainPolicy OID of the subject policy */ - public function __construct( - protected string $_issuerDomainPolicy, - protected string $_subjectDomainPolicy + private function __construct( + private readonly string $issuerDomainPolicy, + private readonly string $subjectDomainPolicy ) { } + public static function create(string $issuerDomainPolicy, string $subjectDomainPolicy): self + { + return new self($issuerDomainPolicy, $subjectDomainPolicy); + } + /** * Initialize from ASN.1. */ @@ -35,7 +40,7 @@ public static function fromASN1(Sequence $seq): self $subject_policy = $seq->at(1) ->asObjectIdentifier() ->oid(); - return new self($issuer_policy, $subject_policy); + return self::create($issuer_policy, $subject_policy); } /** @@ -45,7 +50,7 @@ public static function fromASN1(Sequence $seq): self */ public function issuerDomainPolicy(): string { - return $this->_issuerDomainPolicy; + return $this->issuerDomainPolicy; } /** @@ -55,7 +60,7 @@ public function issuerDomainPolicy(): string */ public function subjectDomainPolicy(): string { - return $this->_subjectDomainPolicy; + return $this->subjectDomainPolicy; } /** @@ -64,8 +69,8 @@ public function subjectDomainPolicy(): string public function toASN1(): Sequence { return Sequence::create( - ObjectIdentifier::create($this->_issuerDomainPolicy), - ObjectIdentifier::create($this->_subjectDomainPolicy) + ObjectIdentifier::create($this->issuerDomainPolicy), + ObjectIdentifier::create($this->subjectDomainPolicy) ); } } diff --git a/src/X509/Certificate/Extension/PolicyMappingsExtension.php b/src/X509/Certificate/Extension/PolicyMappingsExtension.php index aadcbd1c..d2ba7720 100644 --- a/src/X509/Certificate/Extension/PolicyMappingsExtension.php +++ b/src/X509/Certificate/Extension/PolicyMappingsExtension.php @@ -28,15 +28,20 @@ final class PolicyMappingsExtension extends Extension implements Countable, Iter * * @var PolicyMapping[] */ - protected array $_mappings; + private readonly array $mappings; /** * @param PolicyMapping ...$mappings One or more PolicyMapping objects */ - public function __construct(bool $critical, PolicyMapping ...$mappings) + private function __construct(bool $critical, PolicyMapping ...$mappings) { parent::__construct(self::OID_POLICY_MAPPINGS, $critical); - $this->_mappings = $mappings; + $this->mappings = $mappings; + } + + public static function create(bool $critical, PolicyMapping ...$mappings): self + { + return new self($critical, ...$mappings); } /** @@ -46,7 +51,7 @@ public function __construct(bool $critical, PolicyMapping ...$mappings) */ public function mappings(): array { - return $this->_mappings; + return $this->mappings; } /** @@ -60,7 +65,7 @@ public function mappings(): array public function flattenedMappings(): array { $mappings = []; - foreach ($this->_mappings as $mapping) { + foreach ($this->mappings as $mapping) { $idp = $mapping->issuerDomainPolicy(); if (! isset($mappings[$idp])) { $mappings[$idp] = []; @@ -80,7 +85,7 @@ public function flattenedMappings(): array public function issuerMappings(string $oid): array { $oids = []; - foreach ($this->_mappings as $mapping) { + foreach ($this->mappings as $mapping) { if ($mapping->issuerDomainPolicy() === $oid) { $oids[] = $mapping->subjectDomainPolicy(); } @@ -95,7 +100,7 @@ public function issuerMappings(string $oid): array */ public function issuerDomainPolicies(): array { - $idps = array_map(static fn (PolicyMapping $mapping) => $mapping->issuerDomainPolicy(), $this->_mappings); + $idps = array_map(static fn (PolicyMapping $mapping) => $mapping->issuerDomainPolicy(), $this->mappings); return array_values(array_unique($idps)); } @@ -106,7 +111,7 @@ public function issuerDomainPolicies(): array */ public function hasAnyPolicyMapping(): bool { - foreach ($this->_mappings as $mapping) { + foreach ($this->mappings as $mapping) { if ($mapping->issuerDomainPolicy() === PolicyInformation::OID_ANY_POLICY) { return true; } @@ -124,7 +129,7 @@ public function hasAnyPolicyMapping(): bool */ public function count(): int { - return count($this->_mappings); + return count($this->mappings); } /** @@ -134,27 +139,27 @@ public function count(): int */ public function getIterator(): ArrayIterator { - return new ArrayIterator($this->_mappings); + return new ArrayIterator($this->mappings); } - protected static function _fromDER(string $data, bool $critical): static + protected static function fromDER(string $data, bool $critical): static { $mappings = array_map( - fn (UnspecifiedType $el) => PolicyMapping::fromASN1($el->asSequence()), + static fn (UnspecifiedType $el) => PolicyMapping::fromASN1($el->asSequence()), UnspecifiedType::fromDER($data)->asSequence()->elements() ); if (count($mappings) === 0) { throw new UnexpectedValueException('PolicyMappings must have at least one mapping.'); } - return new self($critical, ...$mappings); + return self::create($critical, ...$mappings); } - protected function _valueASN1(): Element + protected function valueASN1(): Element { - if (count($this->_mappings) === 0) { + if (count($this->mappings) === 0) { throw new LogicException('No mappings.'); } - $elements = array_map(static fn (PolicyMapping $mapping) => $mapping->toASN1(), $this->_mappings); + $elements = array_map(static fn (PolicyMapping $mapping) => $mapping->toASN1(), $this->mappings); return Sequence::create(...$elements); } } diff --git a/src/X509/Certificate/Extension/SubjectAlternativeNameExtension.php b/src/X509/Certificate/Extension/SubjectAlternativeNameExtension.php index 79e41eff..7b411404 100644 --- a/src/X509/Certificate/Extension/SubjectAlternativeNameExtension.php +++ b/src/X509/Certificate/Extension/SubjectAlternativeNameExtension.php @@ -15,27 +15,30 @@ */ final class SubjectAlternativeNameExtension extends Extension { - public function __construct( - bool $critical, /** - * Names. - */ - protected GeneralNames $_names + private function __construct( + bool $critical, + private readonly GeneralNames $names ) { parent::__construct(self::OID_SUBJECT_ALT_NAME, $critical); } + public static function create(bool $critical, GeneralNames $names): self + { + return new self($critical, $names); + } + public function names(): GeneralNames { - return $this->_names; + return $this->names; } - protected static function _fromDER(string $data, bool $critical): static + protected static function fromDER(string $data, bool $critical): static { - return new self($critical, GeneralNames::fromASN1(UnspecifiedType::fromDER($data)->asSequence())); + return self::create($critical, GeneralNames::fromASN1(UnspecifiedType::fromDER($data)->asSequence())); } - protected function _valueASN1(): Element + protected function valueASN1(): Element { - return $this->_names->toASN1(); + return $this->names->toASN1(); } } diff --git a/src/X509/Certificate/Extension/SubjectDirectoryAttributesExtension.php b/src/X509/Certificate/Extension/SubjectDirectoryAttributesExtension.php index c609e991..2e2c787a 100644 --- a/src/X509/Certificate/Extension/SubjectDirectoryAttributesExtension.php +++ b/src/X509/Certificate/Extension/SubjectDirectoryAttributesExtension.php @@ -25,15 +25,20 @@ final class SubjectDirectoryAttributesExtension extends Extension implements Cou /** * Attributes. */ - private readonly SequenceOfAttributes $_attributes; + private readonly SequenceOfAttributes $attributes; /** * @param Attribute ...$attribs One or more Attribute objects */ - public function __construct(bool $critical, Attribute ...$attribs) + private function __construct(bool $critical, Attribute ...$attribs) { parent::__construct(self::OID_SUBJECT_DIRECTORY_ATTRIBUTES, $critical); - $this->_attributes = SequenceOfAttributes::create(...$attribs); + $this->attributes = SequenceOfAttributes::create(...$attribs); + } + + public static function create(bool $critical, Attribute ...$attribs): self + { + return new self($critical, ...$attribs); } /** @@ -43,7 +48,7 @@ public function __construct(bool $critical, Attribute ...$attribs) */ public function has(string $name): bool { - return $this->_attributes->has($name); + return $this->attributes->has($name); } /** @@ -53,7 +58,7 @@ public function has(string $name): bool */ public function firstOf(string $name): Attribute { - return $this->_attributes->firstOf($name); + return $this->attributes->firstOf($name); } /** @@ -65,7 +70,7 @@ public function firstOf(string $name): Attribute */ public function allOf(string $name): array { - return $this->_attributes->allOf($name); + return $this->attributes->allOf($name); } /** @@ -75,7 +80,7 @@ public function allOf(string $name): array */ public function all(): array { - return $this->_attributes->all(); + return $this->attributes->all(); } /** @@ -83,7 +88,7 @@ public function all(): array */ public function count(): int { - return count($this->_attributes); + return count($this->attributes); } /** @@ -93,23 +98,23 @@ public function count(): int */ public function getIterator(): ArrayIterator { - return $this->_attributes->getIterator(); + return $this->attributes->getIterator(); } - protected static function _fromDER(string $data, bool $critical): static + protected static function fromDER(string $data, bool $critical): static { $attribs = SequenceOfAttributes::fromASN1(UnspecifiedType::fromDER($data)->asSequence()); if (count($attribs) === 0) { throw new UnexpectedValueException('SubjectDirectoryAttributes must have at least one Attribute.'); } - return new self($critical, ...$attribs->all()); + return self::create($critical, ...$attribs->all()); } - protected function _valueASN1(): Element + protected function valueASN1(): Element { - if (count($this->_attributes) === 0) { + if (count($this->attributes) === 0) { throw new LogicException('No attributes'); } - return $this->_attributes->toASN1(); + return $this->attributes->toASN1(); } } diff --git a/src/X509/Certificate/Extension/SubjectInformationAccessExtension.php b/src/X509/Certificate/Extension/SubjectInformationAccessExtension.php index 909d01d1..7ea45ec5 100644 --- a/src/X509/Certificate/Extension/SubjectInformationAccessExtension.php +++ b/src/X509/Certificate/Extension/SubjectInformationAccessExtension.php @@ -26,12 +26,17 @@ final class SubjectInformationAccessExtension extends Extension implements Count * * @var SubjectAccessDescription[] */ - private readonly array $_accessDescriptions; + private readonly array $accessDescriptions; - public function __construct(bool $critical, SubjectAccessDescription ...$access) + private function __construct(bool $critical, SubjectAccessDescription ...$accessDescriptions) { parent::__construct(self::OID_SUBJECT_INFORMATION_ACCESS, $critical); - $this->_accessDescriptions = $access; + $this->accessDescriptions = $accessDescriptions; + } + + public static function create(bool $critical, SubjectAccessDescription ...$accessDescriptions): self + { + return new self($critical, ...$accessDescriptions); } /** @@ -41,7 +46,7 @@ public function __construct(bool $critical, SubjectAccessDescription ...$access) */ public function accessDescriptions(): array { - return $this->_accessDescriptions; + return $this->accessDescriptions; } /** @@ -51,7 +56,7 @@ public function accessDescriptions(): array */ public function count(): int { - return count($this->_accessDescriptions); + return count($this->accessDescriptions); } /** @@ -62,21 +67,21 @@ public function count(): int */ public function getIterator(): ArrayIterator { - return new ArrayIterator($this->_accessDescriptions); + return new ArrayIterator($this->accessDescriptions); } - protected static function _fromDER(string $data, bool $critical): static + protected static function fromDER(string $data, bool $critical): static { $access = array_map( - fn (UnspecifiedType $el) => SubjectAccessDescription::fromASN1($el->asSequence()), + static fn (UnspecifiedType $el) => SubjectAccessDescription::fromASN1($el->asSequence()), UnspecifiedType::fromDER($data)->asSequence()->elements() ); - return new self($critical, ...$access); + return self::create($critical, ...$access); } - protected function _valueASN1(): Element + protected function valueASN1(): Element { - $elements = array_map(static fn (AccessDescription $access) => $access->toASN1(), $this->_accessDescriptions); + $elements = array_map(static fn (AccessDescription $access) => $access->toASN1(), $this->accessDescriptions); return Sequence::create(...$elements); } } diff --git a/src/X509/Certificate/Extension/SubjectKeyIdentifierExtension.php b/src/X509/Certificate/Extension/SubjectKeyIdentifierExtension.php index 6cd3ee5e..60235234 100644 --- a/src/X509/Certificate/Extension/SubjectKeyIdentifierExtension.php +++ b/src/X509/Certificate/Extension/SubjectKeyIdentifierExtension.php @@ -15,30 +15,33 @@ */ final class SubjectKeyIdentifierExtension extends Extension { - public function __construct( - bool $critical, /** - * Key identifier. - */ - protected string $_keyIdentifier + private function __construct( + bool $critical, + private readonly string $keyIdentifier ) { parent::__construct(self::OID_SUBJECT_KEY_IDENTIFIER, $critical); } + public static function create(bool $critical, string $keyIdentifier): self + { + return new self($critical, $keyIdentifier); + } + /** * Get key identifier. */ public function keyIdentifier(): string { - return $this->_keyIdentifier; + return $this->keyIdentifier; } - protected static function _fromDER(string $data, bool $critical): static + protected static function fromDER(string $data, bool $critical): static { - return new self($critical, UnspecifiedType::fromDER($data)->asOctetString()->string()); + return self::create($critical, UnspecifiedType::fromDER($data)->asOctetString()->string()); } - protected function _valueASN1(): Element + protected function valueASN1(): Element { - return OctetString::create($this->_keyIdentifier); + return OctetString::create($this->keyIdentifier); } } diff --git a/src/X509/Certificate/Extension/Target/Target.php b/src/X509/Certificate/Extension/Target/Target.php index 6d0028fb..6c200723 100644 --- a/src/X509/Certificate/Extension/Target/Target.php +++ b/src/X509/Certificate/Extension/Target/Target.php @@ -22,12 +22,9 @@ abstract class Target public const TYPE_CERT = 2; - /** - * Type tag. - * - * @var int - */ - protected $_type; + protected function __construct(protected int $type) + { + } /** * Generate ASN.1 element. @@ -62,7 +59,7 @@ public static function fromASN1(TaggedType $el): self */ public function type(): int { - return $this->_type; + return $this->type; } /** @@ -70,7 +67,7 @@ public function type(): int */ public function equals(self $other): bool { - if ($this->_type !== $other->_type) { + if ($this->type !== $other->type) { return false; } if ($this->toASN1()->toDER() !== $other->toASN1()->toDER()) { diff --git a/src/X509/Certificate/Extension/Target/TargetGroup.php b/src/X509/Certificate/Extension/Target/TargetGroup.php index 96d1f7f5..870203e1 100644 --- a/src/X509/Certificate/Extension/Target/TargetGroup.php +++ b/src/X509/Certificate/Extension/Target/TargetGroup.php @@ -16,12 +16,15 @@ */ final class TargetGroup extends Target { - public function __construct(/** - * Group name. - */ - protected GeneralName $_name + private function __construct( + private readonly GeneralName $name ) { - $this->_type = self::TYPE_GROUP; + parent::__construct(self::TYPE_GROUP); + } + + public static function create(GeneralName $name): self + { + return new self($name); } /** @@ -29,12 +32,12 @@ public function __construct(/** */ public static function fromChosenASN1(TaggedType $el): Target { - return new self(GeneralName::fromASN1($el)); + return self::create(GeneralName::fromASN1($el)); } public function string(): string { - return $this->_name->string(); + return $this->name->string(); } /** @@ -42,11 +45,11 @@ public function string(): string */ public function name(): GeneralName { - return $this->_name; + return $this->name; } public function toASN1(): Element { - return ExplicitlyTaggedType::create($this->_type, $this->_name->toASN1()); + return ExplicitlyTaggedType::create($this->type, $this->name->toASN1()); } } diff --git a/src/X509/Certificate/Extension/Target/TargetName.php b/src/X509/Certificate/Extension/Target/TargetName.php index d41f996d..ef9bfe4d 100644 --- a/src/X509/Certificate/Extension/Target/TargetName.php +++ b/src/X509/Certificate/Extension/Target/TargetName.php @@ -16,12 +16,15 @@ */ final class TargetName extends Target { - public function __construct(/** - * Name. - */ - protected GeneralName $_name + private function __construct( + private readonly GeneralName $name ) { - $this->_type = self::TYPE_NAME; + parent::__construct(self::TYPE_NAME); + } + + public static function create(GeneralName $name): self + { + return new self($name); } /** @@ -29,21 +32,21 @@ public function __construct(/** */ public static function fromChosenASN1(TaggedType $el): Target { - return new self(GeneralName::fromASN1($el)); + return self::create(GeneralName::fromASN1($el)); } public function string(): string { - return $this->_name->string(); + return $this->name->string(); } public function name(): GeneralName { - return $this->_name; + return $this->name; } public function toASN1(): Element { - return ExplicitlyTaggedType::create($this->_type, $this->_name->toASN1()); + return ExplicitlyTaggedType::create($this->type, $this->name->toASN1()); } } diff --git a/src/X509/Certificate/Extension/Target/Targets.php b/src/X509/Certificate/Extension/Target/Targets.php index 115dbbc4..b1d24ae9 100644 --- a/src/X509/Certificate/Extension/Target/Targets.php +++ b/src/X509/Certificate/Extension/Target/Targets.php @@ -23,11 +23,16 @@ final class Targets implements Countable, IteratorAggregate * * @var Target[] */ - private readonly array $_targets; + private readonly array $targets; - public function __construct(Target ...$targets) + private function __construct(Target ...$targets) { - $this->_targets = $targets; + $this->targets = $targets; + } + + public static function create(Target ...$targets): self + { + return new self(...$targets); } /** @@ -36,7 +41,7 @@ public function __construct(Target ...$targets) public static function fromASN1(Sequence $seq): self { $targets = array_map(static fn (UnspecifiedType $el) => Target::fromASN1($el->asTagged()), $seq->elements()); - return new self(...$targets); + return self::create(...$targets); } /** @@ -46,7 +51,7 @@ public static function fromASN1(Sequence $seq): self */ public function all(): array { - return $this->_targets; + return $this->targets; } /** @@ -56,7 +61,7 @@ public function all(): array */ public function nameTargets(): array { - return $this->_allOfType(Target::TYPE_NAME); + return $this->allOfType(Target::TYPE_NAME); } /** @@ -66,7 +71,7 @@ public function nameTargets(): array */ public function groupTargets(): array { - return $this->_allOfType(Target::TYPE_GROUP); + return $this->allOfType(Target::TYPE_GROUP); } /** @@ -74,7 +79,7 @@ public function groupTargets(): array */ public function hasTarget(Target $target): bool { - foreach ($this->_allOfType($target->type()) as $t) { + foreach ($this->allOfType($target->type()) as $t) { if ($target->equals($t)) { return true; } @@ -87,7 +92,7 @@ public function hasTarget(Target $target): bool */ public function toASN1(): Sequence { - $elements = array_map(static fn (Target $target) => $target->toASN1(), $this->_targets); + $elements = array_map(static fn (Target $target) => $target->toASN1(), $this->targets); return Sequence::create(...$elements); } @@ -96,7 +101,7 @@ public function toASN1(): Sequence */ public function count(): int { - return count($this->_targets); + return count($this->targets); } /** @@ -106,7 +111,7 @@ public function count(): int */ public function getIterator(): ArrayIterator { - return new ArrayIterator($this->_targets); + return new ArrayIterator($this->targets); } /** @@ -114,8 +119,8 @@ public function getIterator(): ArrayIterator * * @return Target[] */ - private function _allOfType(int $type): array + private function allOfType(int $type): array { - return array_values(array_filter($this->_targets, static fn (Target $target) => $target->type() === $type)); + return array_values(array_filter($this->targets, static fn (Target $target) => $target->type() === $type)); } } diff --git a/src/X509/Certificate/Extension/TargetInformationExtension.php b/src/X509/Certificate/Extension/TargetInformationExtension.php index 5f50b3f6..8e1208e9 100644 --- a/src/X509/Certificate/Extension/TargetInformationExtension.php +++ b/src/X509/Certificate/Extension/TargetInformationExtension.php @@ -29,17 +29,17 @@ final class TargetInformationExtension extends Extension implements Countable, I * * @var Targets[] */ - protected array $_targets; + protected array $targets; /** * Targets[] merged to single Targets. */ - private ?Targets $_merged = null; + private ?Targets $merged = null; - public function __construct(bool $critical, Targets ...$targets) + private function __construct(bool $critical, Targets ...$targets) { parent::__construct(self::OID_TARGET_INFORMATION, $critical); - $this->_targets = $targets; + $this->targets = $targets; } /** @@ -47,7 +47,12 @@ public function __construct(bool $critical, Targets ...$targets) */ public function __clone() { - $this->_merged = null; + $this->merged = null; + } + + public static function create(bool $critical, Targets ...$targets): self + { + return new self($critical, ...$targets); } /** @@ -57,7 +62,7 @@ public function __clone() */ public static function fromTargets(Target ...$target): self { - return new self(true, new Targets(...$target)); + return self::create(true, Targets::create(...$target)); } /** @@ -65,14 +70,14 @@ public static function fromTargets(Target ...$target): self */ public function targets(): Targets { - if (! isset($this->_merged)) { + if ($this->merged === null) { $a = []; - foreach ($this->_targets as $targets) { + foreach ($this->targets as $targets) { $a = array_merge($a, $targets->all()); } - $this->_merged = new Targets(...$a); + $this->merged = Targets::create(...$a); } - return $this->_merged; + return $this->merged; } /** @@ -115,18 +120,18 @@ public function getIterator(): ArrayIterator return new ArrayIterator($this->targets()->all()); } - protected static function _fromDER(string $data, bool $critical): static + protected static function fromDER(string $data, bool $critical): static { $targets = array_map( - fn (UnspecifiedType $el) => Targets::fromASN1($el->asSequence()), + static fn (UnspecifiedType $el) => Targets::fromASN1($el->asSequence()), UnspecifiedType::fromDER($data)->asSequence()->elements() ); - return new self($critical, ...$targets); + return self::create($critical, ...$targets); } - protected function _valueASN1(): Element + protected function valueASN1(): Element { - $elements = array_map(static fn (Targets $targets) => $targets->toASN1(), $this->_targets); + $elements = array_map(static fn (Targets $targets) => $targets->toASN1(), $this->targets); return Sequence::create(...$elements); } } diff --git a/src/X509/Certificate/Extension/UnknownExtension.php b/src/X509/Certificate/Extension/UnknownExtension.php index ab00504a..64fea571 100644 --- a/src/X509/Certificate/Extension/UnknownExtension.php +++ b/src/X509/Certificate/Extension/UnknownExtension.php @@ -14,18 +14,18 @@ */ final class UnknownExtension extends Extension { - /** - * Raw extension value. - */ - protected string $_data; - - public function __construct( + private function __construct( string $oid, bool $critical, - protected Element $_element + private readonly Element $element, + private readonly string $data ) { parent::__construct($oid, $critical); - $this->_data = $_element->toDER(); + } + + public static function create(string $oid, bool $critical, Element $element): self + { + return new self($oid, $critical, $element, $element->toDER()); } /** @@ -33,10 +33,7 @@ public function __construct( */ public static function fromRawString(string $oid, bool $critical, string $data): self { - $obj = new self($oid, $critical, OctetString::create('')); - $obj->_element = NullType::create(); - $obj->_data = $data; - return $obj; + return new self($oid, $critical, NullType::create(), $data); } /** @@ -44,20 +41,20 @@ public static function fromRawString(string $oid, bool $critical, string $data): */ public function extensionValue(): string { - return $this->_data; + return $this->data; } - protected function _extnValue(): OctetString + protected function extnValue(): OctetString { - return OctetString::create($this->_data); + return OctetString::create($this->data); } - protected function _valueASN1(): Element + protected function valueASN1(): Element { - return $this->_element; + return $this->element; } - protected static function _fromDER(string $data, bool $critical): static + protected static function fromDER(string $data, bool $critical): static { throw new BadMethodCallException(__FUNCTION__ . ' must be implemented in derived class.'); } diff --git a/src/X509/Certificate/Extensions.php b/src/X509/Certificate/Extensions.php index 51b1a08f..9e558670 100644 --- a/src/X509/Certificate/Extensions.php +++ b/src/X509/Certificate/Extensions.php @@ -42,19 +42,24 @@ final class Extensions implements Countable, IteratorAggregate * * @var Extension[] */ - private array $_extensions; + private array $extensions; /** * @param Extension ...$extensions Extension objects */ - public function __construct(Extension ...$extensions) + private function __construct(Extension ...$extensions) { - $this->_extensions = []; + $this->extensions = []; foreach ($extensions as $ext) { - $this->_extensions[$ext->oid()] = $ext; + $this->extensions[$ext->oid()] = $ext; } } + public static function create(Extension ...$extensions): self + { + return new self(...$extensions); + } + /** * Initialize from ASN.1. */ @@ -64,7 +69,7 @@ public static function fromASN1(Sequence $seq): self static fn (UnspecifiedType $el) => Extension::fromASN1($el->asSequence()), $seq->elements() ); - return new self(...$extensions); + return self::create(...$extensions); } /** @@ -72,7 +77,7 @@ public static function fromASN1(Sequence $seq): self */ public function toASN1(): Sequence { - $elements = array_values(array_map(static fn ($ext) => $ext->toASN1(), $this->_extensions)); + $elements = array_values(array_map(static fn ($ext) => $ext->toASN1(), $this->extensions)); return Sequence::create(...$elements); } @@ -85,7 +90,7 @@ public function withExtensions(Extension ...$exts): self { $obj = clone $this; foreach ($exts as $ext) { - $obj->_extensions[$ext->oid()] = $ext; + $obj->extensions[$ext->oid()] = $ext; } return $obj; } @@ -97,7 +102,7 @@ public function withExtensions(Extension ...$exts): self */ public function has(string $oid): bool { - return isset($this->_extensions[$oid]); + return isset($this->extensions[$oid]); } /** @@ -108,7 +113,7 @@ public function get(string $oid): Extension if (! $this->has($oid)) { throw new LogicException("No extension by OID {$oid}."); } - return $this->_extensions[$oid]; + return $this->extensions[$oid]; } /** @@ -324,7 +329,7 @@ public function inhibitAnyPolicy(): InhibitAnyPolicyExtension */ public function count(): int { - return count($this->_extensions); + return count($this->extensions); } /** @@ -334,6 +339,6 @@ public function count(): int */ public function getIterator(): Traversable { - return new ArrayIterator($this->_extensions); + return new ArrayIterator($this->extensions); } } diff --git a/src/X509/Certificate/TBSCertificate.php b/src/X509/Certificate/TBSCertificate.php index 09c38adb..67fc2b1f 100644 --- a/src/X509/Certificate/TBSCertificate.php +++ b/src/X509/Certificate/TBSCertificate.php @@ -42,48 +42,55 @@ final class TBSCertificate /** * Certificate version. */ - private ?int $_version = null; + private ?int $version = null; /** * Serial number. */ - private ?string $_serialNumber = null; + private ?string $serialNumber = null; /** * Signature algorithm. - * - * @var null|SignatureAlgorithmIdentifier */ - private $_signature; + private ?SignatureAlgorithmIdentifier $signature = null; /** * Issuer unique identifier. */ - private ?UniqueIdentifier $_issuerUniqueID = null; + private ?UniqueIdentifier $issuerUniqueID = null; /** * Subject unique identifier. */ - private ?UniqueIdentifier $_subjectUniqueID = null; + private ?UniqueIdentifier $subjectUniqueID = null; /** * Extensions. */ - private Extensions $_extensions; + private Extensions $extensions; /** - * @param Name $_subject Certificate subject - * @param PublicKeyInfo $_subjectPublicKeyInfo Subject public key - * @param Name $_issuer Certificate issuer - * @param Validity $_validity Validity period + * @param Name $subject Certificate subject + * @param PublicKeyInfo $subjectPublicKeyInfo Subject public key + * @param Name $issuer Certificate issuer + * @param Validity $validity Validity period */ - public function __construct( - protected Name $_subject, - protected PublicKeyInfo $_subjectPublicKeyInfo, - protected Name $_issuer, - protected Validity $_validity + private function __construct( + private Name $subject, + private PublicKeyInfo $subjectPublicKeyInfo, + private Name $issuer, + private Validity $validity ) { - $this->_extensions = new Extensions(); + $this->extensions = Extensions::create(); + } + + public static function create( + Name $subject, + PublicKeyInfo $subjectPublicKeyInfo, + Name $issuer, + Validity $validity + ): self { + return new self($subject, $subjectPublicKeyInfo, $issuer, $validity); } /** @@ -112,26 +119,27 @@ public static function fromASN1(Sequence $seq): self $validity = Validity::fromASN1($seq->at($idx++)->asSequence()); $subject = Name::fromASN1($seq->at($idx++)->asSequence()); $pki = PublicKeyInfo::fromASN1($seq->at($idx++)->asSequence()); - $tbs_cert = new self($subject, $pki, $issuer, $validity); - $tbs_cert->_version = $version; - $tbs_cert->_serialNumber = $serial; - $tbs_cert->_signature = $algo; + $tbs_cert = self::create($subject, $pki, $issuer, $validity) + ->withVersion($version) + ->withSerialNumber($serial) + ->withSignature($algo) + ; if ($seq->hasTagged(1)) { - $tbs_cert->_issuerUniqueID = UniqueIdentifier::fromASN1( + $tbs_cert = $tbs_cert->withIssuerUniqueID(UniqueIdentifier::fromASN1( $seq->getTagged(1) ->asImplicit(Element::TYPE_BIT_STRING) ->asBitString() - ); + )); } if ($seq->hasTagged(2)) { - $tbs_cert->_subjectUniqueID = UniqueIdentifier::fromASN1( + $tbs_cert = $tbs_cert->withSubjectUniqueID(UniqueIdentifier::fromASN1( $seq->getTagged(2) ->asImplicit(Element::TYPE_BIT_STRING) ->asBitString() - ); + )); } if ($seq->hasTagged(3)) { - $tbs_cert->_extensions = Extensions::fromASN1($seq->getTagged(3)->asExplicit()->asSequence()); + $tbs_cert = $tbs_cert->withExtensions(Extensions::fromASN1($seq->getTagged(3)->asExplicit()->asSequence())); } return $tbs_cert; } @@ -144,7 +152,12 @@ public static function fromASN1(Sequence $seq): self public static function fromCSR(CertificationRequest $cr): self { $cri = $cr->certificationRequestInfo(); - $tbs_cert = new self($cri->subject(), $cri->subjectPKInfo(), new Name(), Validity::fromStrings(null, null)); + $tbs_cert = self::create( + $cri->subject(), + $cri->subjectPKInfo(), + Name::create(), + Validity::fromStrings(null, null) + ); // if CSR has Extension Request attribute if ($cri->hasAttributes()) { $attribs = $cri->attributes(); @@ -154,7 +167,7 @@ public static function fromCSR(CertificationRequest $cr): self } // add Subject Key Identifier extension return $tbs_cert->withAdditionalExtensions( - new SubjectKeyIdentifierExtension(false, $cri->subjectPKInfo()->keyIdentifier()) + SubjectKeyIdentifierExtension::create(false, $cri->subjectPKInfo()->keyIdentifier()) ); } @@ -170,13 +183,13 @@ public function withIssuerCertificate(Certificate $cert): self { $obj = clone $this; // set issuer DN from cert's subject - $obj->_issuer = $cert->tbsCertificate() + $obj->issuer = $cert->tbsCertificate() ->subject(); // add authority key identifier extension $key_id = $cert->tbsCertificate() ->subjectPublicKeyInfo() ->keyIdentifier(); - $obj->_extensions = $obj->_extensions->withExtensions(new AuthorityKeyIdentifierExtension(false, $key_id)); + $obj->extensions = $obj->extensions->withExtensions(AuthorityKeyIdentifierExtension::create(false, $key_id)); return $obj; } @@ -188,7 +201,7 @@ public function withIssuerCertificate(Certificate $cert): self public function withVersion(int $version): self { $obj = clone $this; - $obj->_version = $version; + $obj->version = $version; return $obj; } @@ -200,7 +213,7 @@ public function withVersion(int $version): self public function withSerialNumber(int|string $serial): self { $obj = clone $this; - $obj->_serialNumber = strval($serial); + $obj->serialNumber = strval($serial); return $obj; } @@ -226,7 +239,7 @@ public function withRandomSerialNumber(int $size): self public function withSignature(SignatureAlgorithmIdentifier $algo): self { $obj = clone $this; - $obj->_signature = $algo; + $obj->signature = $algo; return $obj; } @@ -236,7 +249,7 @@ public function withSignature(SignatureAlgorithmIdentifier $algo): self public function withIssuer(Name $issuer): self { $obj = clone $this; - $obj->_issuer = $issuer; + $obj->issuer = $issuer; return $obj; } @@ -246,7 +259,7 @@ public function withIssuer(Name $issuer): self public function withValidity(Validity $validity): self { $obj = clone $this; - $obj->_validity = $validity; + $obj->validity = $validity; return $obj; } @@ -256,7 +269,7 @@ public function withValidity(Validity $validity): self public function withSubject(Name $subject): self { $obj = clone $this; - $obj->_subject = $subject; + $obj->subject = $subject; return $obj; } @@ -266,7 +279,7 @@ public function withSubject(Name $subject): self public function withSubjectPublicKeyInfo(PublicKeyInfo $pub_key_info): self { $obj = clone $this; - $obj->_subjectPublicKeyInfo = $pub_key_info; + $obj->subjectPublicKeyInfo = $pub_key_info; return $obj; } @@ -276,7 +289,7 @@ public function withSubjectPublicKeyInfo(PublicKeyInfo $pub_key_info): self public function withIssuerUniqueID(UniqueIdentifier $id): self { $obj = clone $this; - $obj->_issuerUniqueID = $id; + $obj->issuerUniqueID = $id; return $obj; } @@ -286,7 +299,7 @@ public function withIssuerUniqueID(UniqueIdentifier $id): self public function withSubjectUniqueID(UniqueIdentifier $id): self { $obj = clone $this; - $obj->_subjectUniqueID = $id; + $obj->subjectUniqueID = $id; return $obj; } @@ -296,7 +309,7 @@ public function withSubjectUniqueID(UniqueIdentifier $id): self public function withExtensions(Extensions $extensions): self { $obj = clone $this; - $obj->_extensions = $extensions; + $obj->extensions = $extensions; return $obj; } @@ -308,7 +321,7 @@ public function withExtensions(Extensions $extensions): self public function withAdditionalExtensions(Extension ...$exts): self { $obj = clone $this; - $obj->_extensions = $obj->_extensions->withExtensions(...$exts); + $obj->extensions = $obj->extensions->withExtensions(...$exts); return $obj; } @@ -317,7 +330,7 @@ public function withAdditionalExtensions(Extension ...$exts): self */ public function hasVersion(): bool { - return isset($this->_version); + return isset($this->version); } /** @@ -328,7 +341,7 @@ public function version(): int if (! $this->hasVersion()) { throw new LogicException('version not set.'); } - return $this->_version; + return $this->version; } /** @@ -336,7 +349,7 @@ public function version(): int */ public function hasSerialNumber(): bool { - return isset($this->_serialNumber); + return isset($this->serialNumber); } /** @@ -349,7 +362,7 @@ public function serialNumber(): string if (! $this->hasSerialNumber()) { throw new LogicException('serialNumber not set.'); } - return $this->_serialNumber; + return $this->serialNumber; } /** @@ -357,7 +370,7 @@ public function serialNumber(): string */ public function hasSignature(): bool { - return isset($this->_signature); + return isset($this->signature); } /** @@ -368,12 +381,12 @@ public function signature(): SignatureAlgorithmIdentifier if (! $this->hasSignature()) { throw new LogicException('signature not set.'); } - return $this->_signature; + return $this->signature; } public function issuer(): Name { - return $this->_issuer; + return $this->issuer; } /** @@ -381,12 +394,12 @@ public function issuer(): Name */ public function validity(): Validity { - return $this->_validity; + return $this->validity; } public function subject(): Name { - return $this->_subject; + return $this->subject; } /** @@ -394,7 +407,7 @@ public function subject(): Name */ public function subjectPublicKeyInfo(): PublicKeyInfo { - return $this->_subjectPublicKeyInfo; + return $this->subjectPublicKeyInfo; } /** @@ -402,7 +415,7 @@ public function subjectPublicKeyInfo(): PublicKeyInfo */ public function hasIssuerUniqueID(): bool { - return isset($this->_issuerUniqueID); + return isset($this->issuerUniqueID); } public function issuerUniqueID(): UniqueIdentifier @@ -410,7 +423,7 @@ public function issuerUniqueID(): UniqueIdentifier if (! $this->hasIssuerUniqueID()) { throw new LogicException('issuerUniqueID not set.'); } - return $this->_issuerUniqueID; + return $this->issuerUniqueID; } /** @@ -418,7 +431,7 @@ public function issuerUniqueID(): UniqueIdentifier */ public function hasSubjectUniqueID(): bool { - return isset($this->_subjectUniqueID); + return isset($this->subjectUniqueID); } public function subjectUniqueID(): UniqueIdentifier @@ -426,12 +439,12 @@ public function subjectUniqueID(): UniqueIdentifier if (! $this->hasSubjectUniqueID()) { throw new LogicException('subjectUniqueID not set.'); } - return $this->_subjectUniqueID; + return $this->subjectUniqueID; } public function extensions(): Extensions { - return $this->_extensions; + return $this->extensions; } /** @@ -452,19 +465,19 @@ public function toASN1(): Sequence $elements, Integer::create($serial), $signature->toASN1(), - $this->_issuer->toASN1(), - $this->_validity->toASN1(), - $this->_subject->toASN1(), - $this->_subjectPublicKeyInfo->toASN1() + $this->issuer->toASN1(), + $this->validity->toASN1(), + $this->subject->toASN1(), + $this->subjectPublicKeyInfo->toASN1() ); - if (isset($this->_issuerUniqueID)) { - $elements[] = ImplicitlyTaggedType::create(1, $this->_issuerUniqueID->toASN1()); + if (isset($this->issuerUniqueID)) { + $elements[] = ImplicitlyTaggedType::create(1, $this->issuerUniqueID->toASN1()); } - if (isset($this->_subjectUniqueID)) { - $elements[] = ImplicitlyTaggedType::create(2, $this->_subjectUniqueID->toASN1()); + if (isset($this->subjectUniqueID)) { + $elements[] = ImplicitlyTaggedType::create(2, $this->subjectUniqueID->toASN1()); } - if (count($this->_extensions) !== 0) { - $elements[] = ExplicitlyTaggedType::create(3, $this->_extensions->toASN1()); + if (count($this->extensions) !== 0) { + $elements[] = ExplicitlyTaggedType::create(3, $this->extensions->toASN1()); } return Sequence::create(...$elements); } @@ -483,17 +496,17 @@ public function sign( ): Certificate { $crypto ??= Crypto::getDefault(); $tbs_cert = clone $this; - if (! isset($tbs_cert->_version)) { - $tbs_cert->_version = $tbs_cert->_determineVersion(); + if (! isset($tbs_cert->version)) { + $tbs_cert->version = $tbs_cert->_determineVersion(); } - if (! isset($tbs_cert->_serialNumber)) { - $tbs_cert->_serialNumber = strval(0); + if (! isset($tbs_cert->serialNumber)) { + $tbs_cert->serialNumber = '0'; } - $tbs_cert->_signature = $algo; + $tbs_cert->signature = $algo; $data = $tbs_cert->toASN1() ->toDER(); $signature = $crypto->sign($data, $privkey_info, $algo); - return new Certificate($tbs_cert, $algo, $signature); + return Certificate::create($tbs_cert, $algo, $signature); } /** @@ -502,11 +515,11 @@ public function sign( private function _determineVersion(): int { // if extensions are present - if (count($this->_extensions) !== 0) { + if (count($this->extensions) !== 0) { return self::VERSION_3; } // if UniqueIdentifier is present - if (isset($this->_issuerUniqueID) || isset($this->_subjectUniqueID)) { + if (isset($this->issuerUniqueID) || isset($this->subjectUniqueID)) { return self::VERSION_2; } return self::VERSION_1; diff --git a/src/X509/Certificate/Time.php b/src/X509/Certificate/Time.php index 165e7e3e..cd6d0eef 100644 --- a/src/X509/Certificate/Time.php +++ b/src/X509/Certificate/Time.php @@ -5,7 +5,6 @@ namespace SpomkyLabs\Pki\X509\Certificate; use DateTimeImmutable; -use function intval; use SpomkyLabs\Pki\ASN1\Element; use SpomkyLabs\Pki\ASN1\Type\Primitive\GeneralizedTime; use SpomkyLabs\Pki\ASN1\Type\Primitive\UTCTime; @@ -25,14 +24,18 @@ final class Time /** * Time ASN.1 type tag. */ - protected int $_type; + private readonly int $type; - public function __construct(/** - * Datetime. - */ - protected DateTimeImmutable $_dt + private function __construct( + protected DateTimeImmutable $dt, + ?int $type ) { - $this->_type = self::_determineType($_dt); + $this->type = $type ?? self::determineType($dt); + } + + public static function create(DateTimeImmutable $dt): self + { + return new self($dt, null); } /** @@ -40,9 +43,7 @@ public function __construct(/** */ public static function fromASN1(TimeType $el): self { - $obj = new self($el->dateTime()); - $obj->_type = $el->tag(); - return $obj; + return self::create($el->dateTime()); } /** @@ -50,12 +51,12 @@ public static function fromASN1(TimeType $el): self */ public static function fromString(?string $time, ?string $tz = null): self { - return new self(self::_createDateTime($time, $tz)); + return self::create(self::createDateTime($time, $tz)); } public function dateTime(): DateTimeImmutable { - return $this->_dt; + return $this->dt; } /** @@ -63,20 +64,20 @@ public function dateTime(): DateTimeImmutable */ public function toASN1(): TimeType { - $dt = $this->_dt; - switch ($this->_type) { + $dt = $this->dt; + switch ($this->type) { case Element::TYPE_UTC_TIME: return UTCTime::create($dt); case Element::TYPE_GENERALIZED_TIME: // GeneralizedTime must not contain fractional seconds // (rfc5280 4.1.2.5.2) - if (intval($dt->format('u')) !== 0) { + if ((int) $dt->format('u') !== 0) { // remove fractional seconds (round down) - $dt = self::_roundDownFractionalSeconds($dt); + $dt = self::roundDownFractionalSeconds($dt); } return GeneralizedTime::create($dt); } - throw new UnexpectedValueException('Time type ' . Element::tagToName($this->_type) . ' not supported.'); + throw new UnexpectedValueException('Time type ' . Element::tagToName($this->type) . ' not supported.'); } /** @@ -84,7 +85,7 @@ public function toASN1(): TimeType * * @return int Type tag */ - protected static function _determineType(DateTimeImmutable $dt): int + protected static function determineType(DateTimeImmutable $dt): int { if ($dt->format('Y') >= 2050) { return Element::TYPE_GENERALIZED_TIME; diff --git a/src/X509/Certificate/UniqueIdentifier.php b/src/X509/Certificate/UniqueIdentifier.php index 61330859..da6a7f8b 100644 --- a/src/X509/Certificate/UniqueIdentifier.php +++ b/src/X509/Certificate/UniqueIdentifier.php @@ -13,20 +13,22 @@ */ final class UniqueIdentifier { - public function __construct( - /** - * Identifier. - */ - protected BitString $_uid + private function __construct( + private readonly BitString $uid ) { } + public static function create(BitString $uid): self + { + return new self($uid); + } + /** * Initialize from ASN.1. */ public static function fromASN1(BitString $bs): self { - return new self($bs); + return self::create($bs); } /** @@ -34,7 +36,7 @@ public static function fromASN1(BitString $bs): self */ public static function fromString(string $str): self { - return new self(BitString::create($str)); + return self::create(BitString::create($str)); } /** @@ -42,7 +44,7 @@ public static function fromString(string $str): self */ public function string(): string { - return $this->_uid->string(); + return $this->uid->string(); } /** @@ -50,7 +52,7 @@ public function string(): string */ public function bitString(): BitString { - return $this->_uid; + return $this->uid; } /** @@ -58,6 +60,6 @@ public function bitString(): BitString */ public function toASN1(): BitString { - return $this->_uid; + return $this->uid; } } diff --git a/src/X509/Certificate/Validity.php b/src/X509/Certificate/Validity.php index c6f76744..c58c39b9 100644 --- a/src/X509/Certificate/Validity.php +++ b/src/X509/Certificate/Validity.php @@ -13,18 +13,17 @@ */ final class Validity { - public function __construct( - /** - * Not before time. - */ - protected Time $_notBefore, - /** - * Not after time. - */ - protected Time $_notAfter + private function __construct( + private readonly Time $notBefore, + private readonly Time $notAfter ) { } + public static function create(Time $notBefore, Time $notAfter): self + { + return new self($notBefore, $notAfter); + } + /** * Initialize from ASN.1. */ @@ -32,7 +31,7 @@ public static function fromASN1(Sequence $seq): self { $nb = Time::fromASN1($seq->at(0)->asTime()); $na = Time::fromASN1($seq->at(1)->asTime()); - return new self($nb, $na); + return self::create($nb, $na); } /** @@ -44,7 +43,7 @@ public static function fromASN1(Sequence $seq): self */ public static function fromStrings(?string $nb_date, ?string $na_date, ?string $tz = null): self { - return new self(Time::fromString($nb_date, $tz), Time::fromString($na_date, $tz)); + return self::create(Time::fromString($nb_date, $tz), Time::fromString($na_date, $tz)); } /** @@ -52,7 +51,7 @@ public static function fromStrings(?string $nb_date, ?string $na_date, ?string $ */ public function notBefore(): Time { - return $this->_notBefore; + return $this->notBefore; } /** @@ -60,7 +59,7 @@ public function notBefore(): Time */ public function notAfter(): Time { - return $this->_notAfter; + return $this->notAfter; } /** @@ -68,6 +67,6 @@ public function notAfter(): Time */ public function toASN1(): Sequence { - return Sequence::create($this->_notBefore->toASN1(), $this->_notAfter->toASN1()); + return Sequence::create($this->notBefore->toASN1(), $this->notAfter->toASN1()); } } diff --git a/src/X509/CertificationPath/CertificationPath.php b/src/X509/CertificationPath/CertificationPath.php index 4e52034f..6bc9d515 100644 --- a/src/X509/CertificationPath/CertificationPath.php +++ b/src/X509/CertificationPath/CertificationPath.php @@ -33,15 +33,20 @@ final class CertificationPath implements Countable, IteratorAggregate * * @var Certificate[] */ - private readonly array $_certificates; + private readonly array $certificates; /** * @param Certificate ...$certificates Certificates from the trust anchor * to the target end-entity certificate */ - public function __construct(Certificate ...$certificates) + private function __construct(Certificate ...$certificates) { - $this->_certificates = $certificates; + $this->certificates = $certificates; + } + + public static function create(Certificate ...$certificates): self + { + return new self(...$certificates); } /** @@ -49,7 +54,7 @@ public function __construct(Certificate ...$certificates) */ public static function fromCertificateChain(CertificateChain $chain): self { - return new self(...array_reverse($chain->certificates(), false)); + return self::create(...array_reverse($chain->certificates(), false)); } /** @@ -64,8 +69,7 @@ public static function toTarget( CertificateBundle $trust_anchors, ?CertificateBundle $intermediate = null ): self { - $builder = new CertificationPathBuilder($trust_anchors); - return $builder->shortestPathToTarget($target, $intermediate); + return CertificationPathBuilder::create($trust_anchors)->shortestPathToTarget($target, $intermediate); } /** @@ -81,7 +85,7 @@ public static function fromTrustAnchorToTarget( Certificate $target, ?CertificateBundle $intermediate = null ): self { - return self::toTarget($target, new CertificateBundle($trust_anchor), $intermediate); + return self::toTarget($target, CertificateBundle::create($trust_anchor), $intermediate); } /** @@ -91,7 +95,7 @@ public static function fromTrustAnchorToTarget( */ public function certificates(): array { - return $this->_certificates; + return $this->certificates; } /** @@ -99,10 +103,10 @@ public function certificates(): array */ public function trustAnchorCertificate(): Certificate { - if (count($this->_certificates) === 0) { + if (count($this->certificates) === 0) { throw new LogicException('No certificates.'); } - return $this->_certificates[0]; + return $this->certificates[0]; } /** @@ -110,10 +114,10 @@ public function trustAnchorCertificate(): Certificate */ public function endEntityCertificate(): Certificate { - if (count($this->_certificates) === 0) { + if (count($this->certificates) === 0) { throw new LogicException('No certificates.'); } - return $this->_certificates[count($this->_certificates) - 1]; + return $this->certificates[count($this->certificates) - 1]; } /** @@ -121,7 +125,7 @@ public function endEntityCertificate(): Certificate */ public function certificateChain(): CertificateChain { - return new CertificateChain(...array_reverse($this->_certificates, false)); + return CertificateChain::create(...array_reverse($this->certificates, false)); } /** @@ -132,11 +136,11 @@ public function certificateChain(): CertificateChain public function startsWith(Certificate ...$certs): bool { $n = count($certs); - if ($n > count($this->_certificates)) { + if ($n > count($this->certificates)) { return false; } for ($i = 0; $i < $n; ++$i) { - if (! $certs[$i]->equals($this->_certificates[$i])) { + if (! $certs[$i]->equals($this->certificates[$i])) { return false; } } @@ -151,8 +155,7 @@ public function startsWith(Certificate ...$certs): bool public function validate(PathValidationConfig $config, ?Crypto $crypto = null): PathValidationResult { $crypto ??= Crypto::getDefault(); - $validator = new PathValidator($crypto, $config, ...$this->_certificates); - return $validator->validate(); + return PathValidator::create($crypto, $config, ...$this->certificates)->validate(); } /** @@ -160,7 +163,7 @@ public function validate(PathValidationConfig $config, ?Crypto $crypto = null): */ public function count(): int { - return count($this->_certificates); + return count($this->certificates); } /** @@ -170,6 +173,6 @@ public function count(): int */ public function getIterator(): ArrayIterator { - return new ArrayIterator($this->_certificates); + return new ArrayIterator($this->certificates); } } diff --git a/src/X509/CertificationPath/PathBuilding/CertificationPathBuilder.php b/src/X509/CertificationPath/PathBuilding/CertificationPathBuilder.php index d0778cc8..80f535c1 100644 --- a/src/X509/CertificationPath/PathBuilding/CertificationPathBuilder.php +++ b/src/X509/CertificationPath/PathBuilding/CertificationPathBuilder.php @@ -18,12 +18,17 @@ final class CertificationPathBuilder { /** - * @param CertificateBundle $_trustList List of trust anchors + * @param CertificateBundle $trustList List of trust anchors */ - public function __construct(protected CertificateBundle $_trustList) + private function __construct(private readonly CertificateBundle $trustList) { } + public static function create(CertificateBundle $trustList): self + { + return new self($trustList); + } + /** * Get all certification paths to given target certificate from any trust anchor. * @@ -36,11 +41,11 @@ public function allPathsToTarget(Certificate $target, ?CertificateBundle $interm { $paths = $this->resolvePathsToTarget($target, $intermediate); // map paths to CertificationPath objects - return array_map(static fn ($certs) => new CertificationPath(...$certs), $paths); + return array_map(static fn ($certs) => CertificationPath::create(...$certs), $paths); } /** - * Get shortest path to given target certificate from any trust anchor. + * Get the shortest path to given target certificate from any trust anchor. * * @param Certificate $target Target certificate * @param null|CertificateBundle $intermediate Optional intermediate certificates @@ -65,7 +70,7 @@ public function shortestPathToTarget( * * @return Certificate[] */ - private function _findIssuers(Certificate $target, CertificateBundle $bundle): array + private function findIssuers(Certificate $target, CertificateBundle $bundle): array { $issuers = []; $issuer_name = $target->tbsCertificate() @@ -101,7 +106,7 @@ private function resolvePathsToTarget(Certificate $target, ?CertificateBundle $i // array of possible paths $paths = []; // signed by certificate in the trust list - foreach ($this->_findIssuers($target, $this->_trustList) as $issuer) { + foreach ($this->findIssuers($target, $this->trustList) as $issuer) { // if target is self-signed, path consists of only // the target certificate if ($target->equals($issuer)) { @@ -112,7 +117,7 @@ private function resolvePathsToTarget(Certificate $target, ?CertificateBundle $i } if (isset($intermediate)) { // signed by intermediate certificate - foreach ($this->_findIssuers($target, $intermediate) as $issuer) { + foreach ($this->findIssuers($target, $intermediate) as $issuer) { // intermediate certificate must not be self-signed if ($issuer->isSelfIssued()) { continue; diff --git a/src/X509/CertificationPath/PathValidation/PathValidationConfig.php b/src/X509/CertificationPath/PathValidation/PathValidationConfig.php index c8f71b51..3fbf04f6 100644 --- a/src/X509/CertificationPath/PathValidation/PathValidationConfig.php +++ b/src/X509/CertificationPath/PathValidation/PathValidationConfig.php @@ -21,46 +21,51 @@ final class PathValidationConfig * * @var string[] */ - private array $_policySet; + private array $policySet; /** * Trust anchor certificate. * * If not set, path validation uses the first certificate of the path. */ - private ?Certificate $_trustAnchor = null; + private ?Certificate $trustAnchor = null; /** * Whether policy mapping in inhibited. * * Setting this to true disallows policy mapping. */ - private bool $_policyMappingInhibit; + private bool $policyMappingInhibit; /** * Whether the path must be valid for at least one policy in the initial policy set. */ - private bool $_explicitPolicy; + private bool $explicitPolicy; /** * Whether anyPolicy OID processing should be inhibited. * * Setting this to true disallows the usage of anyPolicy. */ - private bool $_anyPolicyInhibit; + private bool $anyPolicyInhibit; /** - * @param DateTimeImmutable $_dateTime Reference date and time - * @param int $_maxLength Maximum certification path length + * @param DateTimeImmutable $dateTime Reference date and time + * @param int $maxLength Maximum certification path length */ - public function __construct( - protected DateTimeImmutable $_dateTime, - protected int $_maxLength + private function __construct( + private DateTimeImmutable $dateTime, + private int $maxLength ) { - $this->_policySet = [PolicyInformation::OID_ANY_POLICY]; - $this->_policyMappingInhibit = false; - $this->_explicitPolicy = false; - $this->_anyPolicyInhibit = false; + $this->policySet = [PolicyInformation::OID_ANY_POLICY]; + $this->policyMappingInhibit = false; + $this->explicitPolicy = false; + $this->anyPolicyInhibit = false; + } + + public static function create(DateTimeImmutable $dateTime, int $maxLength): self + { + return new self($dateTime, $maxLength); } /** @@ -68,7 +73,7 @@ public function __construct( */ public static function defaultConfig(): self { - return new self(new DateTimeImmutable(), 3); + return self::create(new DateTimeImmutable(), 3); } /** @@ -77,7 +82,7 @@ public static function defaultConfig(): self public function withMaxLength(int $length): self { $obj = clone $this; - $obj->_maxLength = $length; + $obj->maxLength = $length; return $obj; } @@ -87,7 +92,7 @@ public function withMaxLength(int $length): self public function withDateTime(DateTimeImmutable $dt): self { $obj = clone $this; - $obj->_dateTime = $dt; + $obj->dateTime = $dt; return $obj; } @@ -97,7 +102,7 @@ public function withDateTime(DateTimeImmutable $dt): self public function withTrustAnchor(Certificate $ca): self { $obj = clone $this; - $obj->_trustAnchor = $ca; + $obj->trustAnchor = $ca; return $obj; } @@ -107,7 +112,7 @@ public function withTrustAnchor(Certificate $ca): self public function withPolicyMappingInhibit(bool $flag): self { $obj = clone $this; - $obj->_policyMappingInhibit = $flag; + $obj->policyMappingInhibit = $flag; return $obj; } @@ -117,7 +122,7 @@ public function withPolicyMappingInhibit(bool $flag): self public function withExplicitPolicy(bool $flag): self { $obj = clone $this; - $obj->_explicitPolicy = $flag; + $obj->explicitPolicy = $flag; return $obj; } @@ -127,7 +132,7 @@ public function withExplicitPolicy(bool $flag): self public function withAnyPolicyInhibit(bool $flag): self { $obj = clone $this; - $obj->_anyPolicyInhibit = $flag; + $obj->anyPolicyInhibit = $flag; return $obj; } @@ -139,7 +144,7 @@ public function withAnyPolicyInhibit(bool $flag): self public function withPolicySet(string ...$policies): self { $obj = clone $this; - $obj->_policySet = $policies; + $obj->policySet = $policies; return $obj; } @@ -148,7 +153,7 @@ public function withPolicySet(string ...$policies): self */ public function maxLength(): int { - return $this->_maxLength; + return $this->maxLength; } /** @@ -156,7 +161,7 @@ public function maxLength(): int */ public function dateTime(): DateTimeImmutable { - return $this->_dateTime; + return $this->dateTime; } /** @@ -166,7 +171,7 @@ public function dateTime(): DateTimeImmutable */ public function policySet(): array { - return $this->_policySet; + return $this->policySet; } /** @@ -174,7 +179,7 @@ public function policySet(): array */ public function hasTrustAnchor(): bool { - return isset($this->_trustAnchor); + return isset($this->trustAnchor); } /** @@ -185,21 +190,21 @@ public function trustAnchor(): Certificate if (! $this->hasTrustAnchor()) { throw new LogicException('No trust anchor.'); } - return $this->_trustAnchor; + return $this->trustAnchor; } public function policyMappingInhibit(): bool { - return $this->_policyMappingInhibit; + return $this->policyMappingInhibit; } public function explicitPolicy(): bool { - return $this->_explicitPolicy; + return $this->explicitPolicy; } public function anyPolicyInhibit(): bool { - return $this->_anyPolicyInhibit; + return $this->anyPolicyInhibit; } } diff --git a/src/X509/CertificationPath/PathValidation/PathValidationResult.php b/src/X509/CertificationPath/PathValidation/PathValidationResult.php index e24847df..292174ca 100644 --- a/src/X509/CertificationPath/PathValidation/PathValidationResult.php +++ b/src/X509/CertificationPath/PathValidation/PathValidationResult.php @@ -24,23 +24,56 @@ final class PathValidationResult * * @var Certificate[] */ - private readonly array $_certificates; + private readonly array $certificates; /** - * @param Certificate[] $certificates Certificates in a certification path - * @param null|PolicyTree $_policyTree Valid policy tree - * @param PublicKeyInfo $_publicKeyInfo Public key of the end-entity certificate - * @param AlgorithmIdentifierType $_publicKeyAlgo Public key algorithm of the end-entity certificate - * @param null|Element $_publicKeyParameters Algorithm parameters + * @param Certificate[] $certificates */ - public function __construct( + private function __construct( array $certificates, - protected ?PolicyTree $_policyTree, - protected PublicKeyInfo $_publicKeyInfo, - protected AlgorithmIdentifierType $_publicKeyAlgo, - protected ?Element $_publicKeyParameters = null + private readonly ?PolicyTree $policyTree, + private readonly PublicKeyInfo $publicKeyInfo, + private readonly AlgorithmIdentifierType $publicKeyAlgo, + private readonly ?Element $publicKeyParameters ) { - $this->_certificates = array_values($certificates); + $this->certificates = array_values($certificates); + } + + /** + * @param Certificate[] $certificates Certificates in a certification path + * @param null|PolicyTree $policyTree Valid policy tree + * @param PublicKeyInfo $publicKeyInfo Public key of the end-entity certificate + * @param AlgorithmIdentifierType $publicKeyAlgo Public key algorithm of the end-entity certificate + * @param null|Element $publicKeyParameters Algorithm parameters + */ + public static function create( + array $certificates, + ?PolicyTree $policyTree, + PublicKeyInfo $publicKeyInfo, + AlgorithmIdentifierType $publicKeyAlgo, + ?Element $publicKeyParameters = null + ): self { + return new self($certificates, $policyTree, $publicKeyInfo, $publicKeyAlgo, $publicKeyParameters); + } + + public function getPolicyTree(): ?PolicyTree + { + return $this->policyTree; + } + + public function getPublicKeyInfo(): PublicKeyInfo + { + return $this->publicKeyInfo; + } + + public function getPublicKeyAlgo(): AlgorithmIdentifierType + { + return $this->publicKeyAlgo; + } + + public function getPublicKeyParameters(): ?Element + { + return $this->publicKeyParameters; } /** @@ -48,7 +81,7 @@ public function __construct( */ public function certificate(): Certificate { - return $this->_certificates[count($this->_certificates) - 1]; + return $this->certificates[count($this->certificates) - 1]; } /** @@ -58,9 +91,9 @@ public function certificate(): Certificate */ public function policies(): array { - if ($this->_policyTree === null) { + if ($this->policyTree === null) { return []; } - return $this->_policyTree->policiesAtDepth(count($this->_certificates)); + return $this->policyTree->policiesAtDepth(count($this->certificates)); } } diff --git a/src/X509/CertificationPath/PathValidation/PathValidator.php b/src/X509/CertificationPath/PathValidation/PathValidator.php index 78f9649e..ba67af4c 100644 --- a/src/X509/CertificationPath/PathValidation/PathValidator.php +++ b/src/X509/CertificationPath/PathValidation/PathValidator.php @@ -26,60 +26,68 @@ final class PathValidator * * @var Certificate[] */ - private readonly array $_certificates; + private readonly array $certificates; /** * Certification path trust anchor. */ - private ?Certificate $_trustAnchor = null; + private ?Certificate $trustAnchor = null; /** - * @param Crypto $_crypto Crypto engine - * @param PathValidationConfig $_config Validation config + * @param Crypto $crypto Crypto engine + * @param PathValidationConfig $config Validation config * @param Certificate ...$certificates Certificates from the trust anchor to * the end-entity certificate */ - public function __construct( - protected Crypto $_crypto, - protected PathValidationConfig $_config, + private function __construct( + protected Crypto $crypto, + protected PathValidationConfig $config, Certificate ...$certificates ) { if (count($certificates) === 0) { throw new LogicException('No certificates.'); } - $this->_certificates = $certificates; + $this->certificates = $certificates; // if trust anchor is explicitly given in configuration - if ($_config->hasTrustAnchor()) { - $this->_trustAnchor = $_config->trustAnchor(); + if ($config->hasTrustAnchor()) { + $this->trustAnchor = $config->trustAnchor(); } else { - $this->_trustAnchor = $certificates[0]; + $this->trustAnchor = $certificates[0]; } } + public static function create( + Crypto $crypto, + PathValidationConfig $config, + Certificate ...$certificates + ): self { + return new self($crypto, $config, ...$certificates); + } + /** * Validate certification path. */ public function validate(): PathValidationResult { - $n = count($this->_certificates); - $state = ValidatorState::initialize($this->_config, $this->_trustAnchor, $n); - for ($i = 0; $i < $n; ++$i) { + $n = count($this->certificates); + $state = ValidatorState::initialize($this->config, $this->trustAnchor, $n); + foreach ($this->certificates as $i => $iValue) { $state = $state->withIndex($i + 1); - $cert = $this->_certificates[$i]; + $cert = $iValue; // process certificate (section 6.1.3.) - $state = $this->_processCertificate($state, $cert); + $state = $this->processCertificate($state, $cert); if (! $state->isFinal()) { // prepare next certificate (section 6.1.4.) - $state = $this->_prepareNext($state, $cert); + $state = $this->prepareNext($state, $cert); } } if (! isset($cert)) { throw new LogicException('No certificates.'); } // wrap-up (section 6.1.5.) - $state = $this->_wrapUp($state, $cert); + $state = $this->wrapUp($state, $cert); // return outputs - return $state->getResult($this->_certificates); + return $state->getResult($this->certificates); } /** @@ -87,23 +95,23 @@ public function validate(): PathValidationResult * * @see https://tools.ietf.org/html/rfc5280#section-6.1.3 */ - private function _processCertificate(ValidatorState $state, Certificate $cert): ValidatorState + private function processCertificate(ValidatorState $state, Certificate $cert): ValidatorState { // (a.1) verify signature - $this->_verifySignature($state, $cert); + $this->verifySignature($state, $cert); // (a.2) check validity period - $this->_checkValidity($cert); + $this->checkValidity($cert); // (a.3) check that certificate is not revoked - $this->_checkRevocation(); + $this->checkRevocation(); // (a.4) check issuer - $this->_checkIssuer($state, $cert); + $this->checkIssuer($state, $cert); // (b)(c) if certificate is self-issued and it is not // the final certificate in the path, skip this step if (! ($cert->isSelfIssued() && ! $state->isFinal())) { // (b) check permitted subtrees - $this->_checkPermittedSubtrees($state); + $this->checkPermittedSubtrees($state); // (c) check excluded subtrees - $this->_checkExcludedSubtrees($state); + $this->checkExcludedSubtrees($state); } $extensions = $cert->tbsCertificate() ->extensions(); @@ -130,34 +138,34 @@ private function _processCertificate(ValidatorState $state, Certificate $cert): * * @see https://tools.ietf.org/html/rfc5280#section-6.1.4 */ - private function _prepareNext(ValidatorState $state, Certificate $cert): ValidatorState + private function prepareNext(ValidatorState $state, Certificate $cert): ValidatorState { // (a)(b) if policy mappings extension is present - $state = $this->_preparePolicyMappings($state, $cert); + $state = $this->preparePolicyMappings($state, $cert); // (c) assign working_issuer_name $state = $state->withWorkingIssuerName($cert->tbsCertificate()->subject()); // (d)(e)(f) - $state = $this->_setPublicKeyState($state, $cert); + $state = $this->setPublicKeyState($state, $cert); // (g) if name constraints extension is present - $state = $this->_prepareNameConstraints($state, $cert); + $state = $this->prepareNameConstraints($state, $cert); // (h) if certificate is not self-issued if (! $cert->isSelfIssued()) { - $state = $this->_prepareNonSelfIssued($state); + $state = $this->prepareNonSelfIssued($state); } // (i) if policy constraints extension is present - $state = $this->_preparePolicyConstraints($state, $cert); + $state = $this->preparePolicyConstraints($state, $cert); // (j) if inhibit any policy extension is present - $state = $this->_prepareInhibitAnyPolicy($state, $cert); + $state = $this->prepareInhibitAnyPolicy($state, $cert); // (k) check basic constraints - $this->_processBasicContraints($cert); + $this->processBasicContraints($cert); // (l) verify max_path_length - $state = $this->_verifyMaxPathLength($state, $cert); + $state = $this->verifyMaxPathLength($state, $cert); // (m) check pathLenContraint - $state = $this->_processPathLengthContraint($state, $cert); + $state = $this->processPathLengthContraint($state, $cert); // (n) check key usage - $this->_checkKeyUsage($cert); + $this->checkKeyUsage($cert); // (o) process relevant extensions - return $this->_processExtensions($state); + return $this->processExtensions($state); } /** @@ -165,7 +173,7 @@ private function _prepareNext(ValidatorState $state, Certificate $cert): Validat * * @see https://tools.ietf.org/html/rfc5280#section-6.1.5 */ - private function _wrapUp(ValidatorState $state, Certificate $cert): ValidatorState + private function wrapUp(ValidatorState $state, Certificate $cert): ValidatorState { $tbs_cert = $cert->tbsCertificate(); $extensions = $tbs_cert->extensions(); @@ -182,11 +190,11 @@ private function _wrapUp(ValidatorState $state, Certificate $cert): ValidatorSta } } // (c)(d)(e) - $state = $this->_setPublicKeyState($state, $cert); + $state = $this->setPublicKeyState($state, $cert); // (f) process relevant extensions - $state = $this->_processExtensions($state); + $state = $this->processExtensions($state); // (g) intersection of valid_policy_tree and the initial-policy-set - $state = $this->_calculatePolicyIntersection($state); + $state = $this->calculatePolicyIntersection($state); // check that explicit_policy > 0 or valid_policy_tree is set if (! ($state->explicitPolicy() > 0 || $state->hasValidPolicyTree())) { throw new PathValidationException('No valid policies.'); @@ -199,7 +207,7 @@ private function _wrapUp(ValidatorState $state, Certificate $cert): ValidatorSta * Update working_public_key, working_public_key_parameters and working_public_key_algorithm state variables from * certificate. */ - private function _setPublicKeyState(ValidatorState $state, Certificate $cert): ValidatorState + private function setPublicKeyState(ValidatorState $state, Certificate $cert): ValidatorState { $pk_info = $cert->tbsCertificate() ->subjectPublicKeyInfo(); @@ -224,10 +232,10 @@ private function _setPublicKeyState(ValidatorState $state, Certificate $cert): V /** * Verify certificate signature. */ - private function _verifySignature(ValidatorState $state, Certificate $cert): void + private function verifySignature(ValidatorState $state, Certificate $cert): void { try { - $valid = $cert->verify($state->workingPublicKey(), $this->_crypto); + $valid = $cert->verify($state->workingPublicKey(), $this->crypto); } catch (RuntimeException $e) { throw new PathValidationException('Failed to verify signature: ' . $e->getMessage(), 0, $e); } @@ -239,9 +247,9 @@ private function _verifySignature(ValidatorState $state, Certificate $cert): voi /** * Check certificate validity. */ - private function _checkValidity(Certificate $cert): void + private function checkValidity(Certificate $cert): void { - $refdt = $this->_config->dateTime(); + $refdt = $this->config->dateTime(); $validity = $cert->tbsCertificate() ->validity(); if ($validity->notBefore()->dateTime()->diff($refdt)->invert !== 0) { @@ -255,7 +263,7 @@ private function _checkValidity(Certificate $cert): void /** * Check certificate revocation. */ - private function _checkRevocation(): void + private function checkRevocation(): void { // @todo Implement CRL handling } @@ -263,20 +271,20 @@ private function _checkRevocation(): void /** * Check certificate issuer. */ - private function _checkIssuer(ValidatorState $state, Certificate $cert): void + private function checkIssuer(ValidatorState $state, Certificate $cert): void { if (! $cert->tbsCertificate()->issuer()->equals($state->workingIssuerName())) { throw new PathValidationException('Certification issuer mismatch.'); } } - private function _checkPermittedSubtrees(ValidatorState $state): void + private function checkPermittedSubtrees(ValidatorState $state): void { // @todo Implement $state->permittedSubtrees(); } - private function _checkExcludedSubtrees(ValidatorState $state): void + private function checkExcludedSubtrees(ValidatorState $state): void { // @todo Implement $state->excludedSubtrees(); @@ -285,7 +293,7 @@ private function _checkExcludedSubtrees(ValidatorState $state): void /** * Apply policy mappings handling for the preparation step. */ - private function _preparePolicyMappings(ValidatorState $state, Certificate $cert): ValidatorState + private function preparePolicyMappings(ValidatorState $state, Certificate $cert): ValidatorState { $extensions = $cert->tbsCertificate() ->extensions(); @@ -306,12 +314,12 @@ private function _preparePolicyMappings(ValidatorState $state, Certificate $cert /** * Apply name constraints handling for the preparation step. */ - private function _prepareNameConstraints(ValidatorState $state, Certificate $cert): ValidatorState + private function prepareNameConstraints(ValidatorState $state, Certificate $cert): ValidatorState { $extensions = $cert->tbsCertificate() ->extensions(); if ($extensions->hasNameConstraints()) { - $state = $this->_processNameConstraints($state); + $state = $this->processNameConstraints($state); } return $state; } @@ -319,7 +327,7 @@ private function _prepareNameConstraints(ValidatorState $state, Certificate $cer /** * Apply preparation for a non-self-signed certificate. */ - private function _prepareNonSelfIssued(ValidatorState $state): ValidatorState + private function prepareNonSelfIssued(ValidatorState $state): ValidatorState { // (h.1) if ($state->explicitPolicy() > 0) { @@ -339,7 +347,7 @@ private function _prepareNonSelfIssued(ValidatorState $state): ValidatorState /** * Apply policy constraints handling for the preparation step. */ - private function _preparePolicyConstraints(ValidatorState $state, Certificate $cert): ValidatorState + private function preparePolicyConstraints(ValidatorState $state, Certificate $cert): ValidatorState { $extensions = $cert->tbsCertificate() ->extensions(); @@ -363,7 +371,7 @@ private function _preparePolicyConstraints(ValidatorState $state, Certificate $c /** * Apply inhibit any-policy handling for the preparation step. */ - private function _prepareInhibitAnyPolicy(ValidatorState $state, Certificate $cert): ValidatorState + private function prepareInhibitAnyPolicy(ValidatorState $state, Certificate $cert): ValidatorState { $extensions = $cert->tbsCertificate() ->extensions(); @@ -379,7 +387,7 @@ private function _prepareInhibitAnyPolicy(ValidatorState $state, Certificate $ce /** * Verify maximum certification path length for the preparation step. */ - private function _verifyMaxPathLength(ValidatorState $state, Certificate $cert): ValidatorState + private function verifyMaxPathLength(ValidatorState $state, Certificate $cert): ValidatorState { if (! $cert->isSelfIssued()) { if ($state->maxPathLength() <= 0) { @@ -393,7 +401,7 @@ private function _verifyMaxPathLength(ValidatorState $state, Certificate $cert): /** * Check key usage extension for the preparation step. */ - private function _checkKeyUsage(Certificate $cert): void + private function checkKeyUsage(Certificate $cert): void { $extensions = $cert->tbsCertificate() ->extensions(); @@ -405,7 +413,7 @@ private function _checkKeyUsage(Certificate $cert): void } } - private function _processNameConstraints(ValidatorState $state): ValidatorState + private function processNameConstraints(ValidatorState $state): ValidatorState { // @todo Implement return $state; @@ -414,7 +422,7 @@ private function _processNameConstraints(ValidatorState $state): ValidatorState /** * Process basic constraints extension. */ - private function _processBasicContraints(Certificate $cert): void + private function processBasicContraints(Certificate $cert): void { if ($cert->tbsCertificate()->version() === TBSCertificate::VERSION_3) { $extensions = $cert->tbsCertificate() @@ -432,7 +440,7 @@ private function _processBasicContraints(Certificate $cert): void /** * Process pathLenConstraint. */ - private function _processPathLengthContraint(ValidatorState $state, Certificate $cert): ValidatorState + private function processPathLengthContraint(ValidatorState $state, Certificate $cert): ValidatorState { $extensions = $cert->tbsCertificate() ->extensions(); @@ -447,13 +455,13 @@ private function _processPathLengthContraint(ValidatorState $state, Certificate return $state; } - private function _processExtensions(ValidatorState $state): ValidatorState + private function processExtensions(ValidatorState $state): ValidatorState { // @todo Implement return $state; } - private function _calculatePolicyIntersection(ValidatorState $state): ValidatorState + private function calculatePolicyIntersection(ValidatorState $state): ValidatorState { // (i) If the valid_policy_tree is NULL, the intersection is NULL if (! $state->hasValidPolicyTree()) { @@ -462,7 +470,7 @@ private function _calculatePolicyIntersection(ValidatorState $state): ValidatorS // (ii) If the valid_policy_tree is not NULL and // the user-initial-policy-set is any-policy, the intersection // is the entire valid_policy_tree - $initial_policies = $this->_config->policySet(); + $initial_policies = $this->config->policySet(); if (in_array(PolicyInformation::OID_ANY_POLICY, $initial_policies, true)) { return $state; } diff --git a/src/X509/CertificationPath/PathValidation/ValidatorState.php b/src/X509/CertificationPath/PathValidation/ValidatorState.php index 8c620c4e..9415601b 100644 --- a/src/X509/CertificationPath/PathValidation/ValidatorState.php +++ b/src/X509/CertificationPath/PathValidation/ValidatorState.php @@ -130,7 +130,7 @@ public static function initialize(PathValidationConfig $config, Certificate $tru $state = new self(); $state->_pathLength = $n; $state->_index = 1; - $state->_validPolicyTree = new PolicyTree(PolicyNode::anyPolicyNode()); + $state->_validPolicyTree = PolicyTree::create(PolicyNode::anyPolicyNode()); $state->_permittedSubtrees = null; $state->_excludedSubtrees = null; $state->_explicitPolicy = $config->explicitPolicy() ? 0 : $n + 1; @@ -357,7 +357,7 @@ public function isFinal(): bool */ public function getResult(array $certificates): PathValidationResult { - return new PathValidationResult( + return PathValidationResult::create( $certificates, $this->_validPolicyTree, $this->_workingPublicKey, diff --git a/src/X509/CertificationPath/Policy/PolicyNode.php b/src/X509/CertificationPath/Policy/PolicyNode.php index 65fe66c3..ede2a995 100644 --- a/src/X509/CertificationPath/Policy/PolicyNode.php +++ b/src/X509/CertificationPath/Policy/PolicyNode.php @@ -26,30 +26,32 @@ final class PolicyNode implements IteratorAggregate, Countable * * @var PolicyNode[] */ - private array $_children; + private array $children; /** * Reference to the parent node. - * - * @var null|PolicyNode */ - private $_parent; + private PolicyNode|null $parent = null; /** - * @param string $_validPolicy Policy OID - * @param PolicyQualifierInfo[] $_qualifiers - * @param string[] $_expectedPolicies - */ - public function __construct( - private readonly string $_validPolicy, /** - * List of qualifiers. + * @param PolicyQualifierInfo[] $qualifiers + * @param string[] $expectedPolicies */ - private readonly array $_qualifiers, /** - * List of expected policy OIDs. - */ - private array $_expectedPolicies + private function __construct( + private readonly string $validPolicy, + private readonly array $qualifiers, + private array $expectedPolicies ) { - $this->_children = []; + $this->children = []; + } + + /** + * @param PolicyQualifierInfo[] $qualifiers + * @param string[] $expectedPolicies + */ + public static function create(string $validPolicy, array $qualifiers, array $expectedPolicies): self + { + return new self($validPolicy, $qualifiers, $expectedPolicies); } /** @@ -57,7 +59,7 @@ public function __construct( */ public static function anyPolicyNode(): self { - return new self(PolicyInformation::OID_ANY_POLICY, [], [PolicyInformation::OID_ANY_POLICY]); + return self::create(PolicyInformation::OID_ANY_POLICY, [], [PolicyInformation::OID_ANY_POLICY]); } /** @@ -65,7 +67,7 @@ public static function anyPolicyNode(): self */ public function validPolicy(): string { - return $this->_validPolicy; + return $this->validPolicy; } /** @@ -73,7 +75,7 @@ public function validPolicy(): string */ public function isAnyPolicy(): bool { - return $this->_validPolicy === PolicyInformation::OID_ANY_POLICY; + return $this->validPolicy === PolicyInformation::OID_ANY_POLICY; } /** @@ -83,7 +85,7 @@ public function isAnyPolicy(): bool */ public function qualifiers(): array { - return $this->_qualifiers; + return $this->qualifiers; } /** @@ -91,7 +93,7 @@ public function qualifiers(): array */ public function hasExpectedPolicy(string $oid): bool { - return in_array($oid, $this->_expectedPolicies, true); + return in_array($oid, $this->expectedPolicies, true); } /** @@ -101,7 +103,7 @@ public function hasExpectedPolicy(string $oid): bool */ public function expectedPolicies(): array { - return $this->_expectedPolicies; + return $this->expectedPolicies; } /** @@ -111,7 +113,7 @@ public function expectedPolicies(): array */ public function setExpectedPolicies(string ...$oids): void { - $this->_expectedPolicies = $oids; + $this->expectedPolicies = $oids; } /** @@ -119,7 +121,7 @@ public function setExpectedPolicies(string ...$oids): void */ public function hasChildWithValidPolicy(string $oid): bool { - foreach ($this->_children as $node) { + foreach ($this->children as $node) { if ($node->validPolicy() === $oid) { return true; } @@ -133,8 +135,8 @@ public function hasChildWithValidPolicy(string $oid): bool public function addChild(self $node): self { $id = spl_object_hash($node); - $node->_parent = $this; - $this->_children[$id] = $node; + $node->parent = $this; + $this->children[$id] = $node; return $this; } @@ -145,7 +147,7 @@ public function addChild(self $node): self */ public function children(): array { - return array_values($this->_children); + return array_values($this->children); } /** @@ -155,9 +157,9 @@ public function children(): array */ public function remove(): self { - if ($this->_parent !== null) { + if ($this->parent !== null) { $id = spl_object_hash($this); - unset($this->_parent->_children[$id], $this->_parent); + unset($this->parent->children[$id], $this->parent); } return $this; } @@ -167,7 +169,7 @@ public function remove(): self */ public function hasParent(): bool { - return isset($this->_parent); + return isset($this->parent); } /** @@ -175,7 +177,7 @@ public function hasParent(): bool */ public function parent(): ?self { - return $this->_parent; + return $this->parent; } /** @@ -185,11 +187,11 @@ public function parent(): ?self */ public function parents(): array { - if ($this->_parent === null) { + if ($this->parent === null) { return []; } - $nodes = $this->_parent->parents(); - $nodes[] = $this->_parent; + $nodes = $this->parent->parents(); + $nodes[] = $this->parent; return array_reverse($nodes); } @@ -200,7 +202,7 @@ public function parents(): array */ public function walkNodes(callable $fn): void { - foreach ($this->_children as $node) { + foreach ($this->children as $node) { $node->walkNodes($fn); } $fn($this); @@ -212,7 +214,7 @@ public function walkNodes(callable $fn): void public function nodeCount(): int { $c = 1; - foreach ($this->_children as $child) { + foreach ($this->children as $child) { $c += $child->nodeCount(); } return $c; @@ -225,7 +227,7 @@ public function nodeCount(): int */ public function count(): int { - return count($this->_children); + return count($this->children); } /** @@ -235,6 +237,6 @@ public function count(): int */ public function getIterator(): ArrayIterator { - return new ArrayIterator($this->_children); + return new ArrayIterator($this->children); } } diff --git a/src/X509/CertificationPath/Policy/PolicyTree.php b/src/X509/CertificationPath/Policy/PolicyTree.php index 9e6b045e..914f7258 100644 --- a/src/X509/CertificationPath/Policy/PolicyTree.php +++ b/src/X509/CertificationPath/Policy/PolicyTree.php @@ -14,12 +14,17 @@ final class PolicyTree { /** - * @param PolicyNode $_root Initial root node + * @param PolicyNode $root Initial root node */ - public function __construct(protected ?PolicyNode $_root) + private function __construct(private ?PolicyNode $root) { } + public static function create(?PolicyNode $root): self + { + return new self($root); + } + /** * Process policy information from the certificate. * @@ -35,13 +40,13 @@ public function processPolicies(ValidatorState $state, Certificate $cert): Valid foreach ($policies as $policy) { /** @var PolicyInformation $policy */ if ($policy->isAnyPolicy()) { - $tree->_processAnyPolicy($policy, $cert, $state); + $tree->processAnyPolicy($policy, $cert, $state); } else { - $tree->_processPolicy($policy, $state); + $tree->processPolicy($policy, $state); } } // if whole tree is pruned - if ($tree->_pruneTree($state->index() - 1) === 0) { + if ($tree->pruneTree($state->index() - 1) === 0) { return $state->withoutValidPolicyTree(); } return $state->withValidPolicyTree($tree); @@ -59,7 +64,7 @@ public function processMappings(ValidatorState $state, Certificate $cert): Valid $tree->_deleteMappings($cert, $state); } // if whole tree is pruned - if ($tree->_root === null) { + if ($tree->root === null) { return $state->withoutValidPolicyTree(); } return $state->withValidPolicyTree($tree); @@ -73,7 +78,7 @@ public function processMappings(ValidatorState $state, Certificate $cert): Valid public function calculateIntersection(ValidatorState $state, array $policies): ValidatorState { $tree = clone $this; - $valid_policy_node_set = $tree->_validPolicyNodeSet(); + $valid_policy_node_set = $tree->validPolicyNodeSet(); // 2. If the valid_policy of any node in the valid_policy_node_set // is not in the user-initial-policy-set and is not anyPolicy, // delete this node and all its children. @@ -95,7 +100,7 @@ function (PolicyNode $node) use ($policies) { // 3. If the valid_policy_tree includes a node of depth n with // the valid_policy anyPolicy and the user-initial-policy-set // is not any-policy - foreach ($tree->_nodesAtDepth($state->index()) as $node) { + foreach ($tree->nodesAtDepth($state->index()) as $node) { if ($node->hasParent() && $node->isAnyPolicy()) { // a. Set P-Q to the qualifier_set in the node of depth n // with valid_policy anyPolicy. @@ -105,13 +110,13 @@ function (PolicyNode $node) use ($policies) { // create a child node whose parent is the node of depth n-1 // with the valid_policy anyPolicy. $poids = array_diff($policies, $valid_policy_set); - foreach ($tree->_nodesAtDepth($state->index() - 1) as $parent) { + foreach ($tree->nodesAtDepth($state->index() - 1) as $parent) { if ($parent->isAnyPolicy()) { // Set the values in the child node as follows: // set the valid_policy to P-OID, set the qualifier_set // to P-Q, and set the expected_policy_set to {P-OID}. foreach ($poids as $poid) { - $parent->addChild(new PolicyNode($poid, $pq, [$poid])); + $parent->addChild(PolicyNode::create($poid, $pq, [$poid])); } break; } @@ -124,7 +129,7 @@ function (PolicyNode $node) use ($policies) { // 4. If there is a node in the valid_policy_tree of depth n-1 or less // without any child nodes, delete that node. Repeat this step until // there are no nodes of depth n-1 or less without children. - if ($tree->_pruneTree($state->index() - 1) === 0) { + if ($tree->pruneTree($state->index() - 1) === 0) { return $state->withoutValidPolicyTree(); } return $state->withValidPolicyTree($tree); @@ -140,8 +145,8 @@ function (PolicyNode $node) use ($policies) { public function policiesAtDepth(int $i): array { $policies = []; - foreach ($this->_nodesAtDepth($i) as $node) { - $policies[] = new PolicyInformation($node->validPolicy(), ...$node->qualifiers()); + foreach ($this->nodesAtDepth($i) as $node) { + $policies[] = PolicyInformation::create($node->validPolicy(), ...$node->qualifiers()); } return $policies; } @@ -149,16 +154,16 @@ public function policiesAtDepth(int $i): array /** * Process single policy information. */ - private function _processPolicy(PolicyInformation $policy, ValidatorState $state): void + private function processPolicy(PolicyInformation $policy, ValidatorState $state): void { $p_oid = $policy->oid(); $i = $state->index(); $match_count = 0; // (d.1.i) for each node of depth i-1 in the valid_policy_tree... - foreach ($this->_nodesAtDepth($i - 1) as $node) { + foreach ($this->nodesAtDepth($i - 1) as $node) { // ...where P-OID is in the expected_policy_set if ($node->hasExpectedPolicy($p_oid)) { - $node->addChild(new PolicyNode($p_oid, $policy->qualifiers(), [$p_oid])); + $node->addChild(PolicyNode::create($p_oid, $policy->qualifiers(), [$p_oid])); ++$match_count; } } @@ -166,9 +171,9 @@ private function _processPolicy(PolicyInformation $policy, ValidatorState $state if ($match_count === 0) { // ...and the valid_policy_tree includes a node of depth i-1 with // the valid_policy anyPolicy - foreach ($this->_nodesAtDepth($i - 1) as $node) { + foreach ($this->nodesAtDepth($i - 1) as $node) { if ($node->isAnyPolicy()) { - $node->addChild(new PolicyNode($p_oid, $policy->qualifiers(), [$p_oid])); + $node->addChild(PolicyNode::create($p_oid, $policy->qualifiers(), [$p_oid])); } } } @@ -177,7 +182,7 @@ private function _processPolicy(PolicyInformation $policy, ValidatorState $state /** * Process anyPolicy policy information. */ - private function _processAnyPolicy(PolicyInformation $policy, Certificate $cert, ValidatorState $state): void + private function processAnyPolicy(PolicyInformation $policy, Certificate $cert, ValidatorState $state): void { $i = $state->index(); // if (a) inhibit_anyPolicy is greater than 0 or @@ -187,12 +192,12 @@ private function _processAnyPolicy(PolicyInformation $policy, Certificate $cert, return; } // for each node in the valid_policy_tree of depth i-1 - foreach ($this->_nodesAtDepth($i - 1) as $node) { + foreach ($this->nodesAtDepth($i - 1) as $node) { // for each value in the expected_policy_set foreach ($node->expectedPolicies() as $p_oid) { // that does not appear in a child node if (! $node->hasChildWithValidPolicy($p_oid)) { - $node->addChild(new PolicyNode($p_oid, $policy->qualifiers(), [$p_oid])); + $node->addChild(PolicyNode::create($p_oid, $policy->qualifiers(), [$p_oid])); } } } @@ -209,7 +214,7 @@ private function _applyMappings(Certificate $cert, ValidatorState $state): void // (6.1.4. b.1.) for each node in the valid_policy_tree of depth i... foreach ($policy_mappings->flattenedMappings() as $idp => $sdps) { $match_count = 0; - foreach ($this->_nodesAtDepth($state->index()) as $node) { + foreach ($this->nodesAtDepth($state->index()) as $node) { // ...where ID-P is the valid_policy if ($node->validPolicy() === $idp) { // set expected_policy_set to the set of subjectDomainPolicy @@ -241,11 +246,11 @@ private function _applyAnyPolicyMapping( ): void { // (6.1.4. b.1.) ...but there is a node of depth i with // a valid_policy of anyPolicy - foreach ($this->_nodesAtDepth($state->index()) as $node) { + foreach ($this->nodesAtDepth($state->index()) as $node) { if ($node->isAnyPolicy()) { // then generate a child node of the node of depth i-1 // that has a valid_policy of anyPolicy as follows... - foreach ($this->_nodesAtDepth($state->index() - 1) as $subnode) { + foreach ($this->nodesAtDepth($state->index() - 1) as $subnode) { if ($subnode->isAnyPolicy()) { // try to fetch qualifiers of anyPolicy certificate policy try { @@ -258,7 +263,7 @@ private function _applyAnyPolicyMapping( // if there's no policies or no qualifiers $qualifiers = []; } - $subnode->addChild(new PolicyNode($idp, $qualifiers, $sdps)); + $subnode->addChild(PolicyNode::create($idp, $qualifiers, $sdps)); // bail after first anyPolicy has been processed break; } @@ -280,12 +285,12 @@ private function _deleteMappings(Certificate $cert, ValidatorState $state): void ->issuerDomainPolicies(); // delete each node of depth i in the valid_policy_tree // where ID-P is the valid_policy - foreach ($this->_nodesAtDepth($state->index()) as $node) { + foreach ($this->nodesAtDepth($state->index()) as $node) { if (in_array($node->validPolicy(), $idps, true)) { $node->remove(); } } - $this->_pruneTree($state->index() - 1); + $this->pruneTree($state->index() - 1); } /** @@ -293,24 +298,24 @@ private function _deleteMappings(Certificate $cert, ValidatorState $state): void * * @return int The number of nodes left in a tree */ - private function _pruneTree(int $depth): int + private function pruneTree(int $depth): int { - if ($this->_root === null) { + if ($this->root === null) { return 0; } for ($i = $depth; $i > 0; --$i) { - foreach ($this->_nodesAtDepth($i) as $node) { + foreach ($this->nodesAtDepth($i) as $node) { if (count($node) === 0) { $node->remove(); } } } // if root has no children left - if (count($this->_root) === 0) { - $this->_root = null; + if (count($this->root) === 0) { + $this->root = null; return 0; } - return $this->_root->nodeCount(); + return $this->root->nodeCount(); } /** @@ -318,15 +323,15 @@ private function _pruneTree(int $depth): int * * @return PolicyNode[] */ - private function _nodesAtDepth(int $i): array + private function nodesAtDepth(int $i): array { - if ($this->_root === null) { + if ($this->root === null) { return []; } $depth = 0; - $nodes = [$this->_root]; + $nodes = [$this->root]; while ($depth < $i) { - $nodes = self::_gatherChildren(...$nodes); + $nodes = self::gatherChildren(...$nodes); if (count($nodes) === 0) { break; } @@ -340,16 +345,16 @@ private function _nodesAtDepth(int $i): array * * @return PolicyNode[] */ - private function _validPolicyNodeSet(): array + private function validPolicyNodeSet(): array { // 1. Determine the set of policy nodes whose parent nodes have // a valid_policy of anyPolicy. This is the valid_policy_node_set. $set = []; - if ($this->_root === null) { + if ($this->root === null) { return $set; } // for each node in a tree - $this->_root->walkNodes( + $this->root->walkNodes( function (PolicyNode $node) use (&$set) { $parents = $node->parents(); // node has parents @@ -372,7 +377,7 @@ function (PolicyNode $node) use (&$set) { * * @return PolicyNode[] */ - private static function _gatherChildren(PolicyNode ...$nodes): array + private static function gatherChildren(PolicyNode ...$nodes): array { $children = []; foreach ($nodes as $node) { diff --git a/src/X509/CertificationRequest/Attribute/ExtensionRequestValue.php b/src/X509/CertificationRequest/Attribute/ExtensionRequestValue.php index 8b7f77a8..1b9e6868 100644 --- a/src/X509/CertificationRequest/Attribute/ExtensionRequestValue.php +++ b/src/X509/CertificationRequest/Attribute/ExtensionRequestValue.php @@ -21,20 +21,25 @@ final class ExtensionRequestValue extends AttributeValue final public const OID = '1.2.840.113549.1.9.14'; /** - * @param Extensions $_extensions Extensions. + * @param Extensions $extensions Extensions. */ - public function __construct( - protected Extensions $_extensions + private function __construct( + protected Extensions $extensions ) { parent::__construct(self::OID); } + public static function create(Extensions $extensions): self + { + return new self($extensions); + } + /** * @return self */ public static function fromASN1(UnspecifiedType $el): AttributeValue { - return new self(Extensions::fromASN1($el->asSequence())); + return self::create(Extensions::fromASN1($el->asSequence())); } /** @@ -42,12 +47,12 @@ public static function fromASN1(UnspecifiedType $el): AttributeValue */ public function extensions(): Extensions { - return $this->_extensions; + return $this->extensions; } public function toASN1(): Element { - return $this->_extensions->toASN1(); + return $this->extensions->toASN1(); } public function stringValue(): string diff --git a/src/X509/CertificationRequest/CertificationRequest.php b/src/X509/CertificationRequest/CertificationRequest.php index dfd66efd..300385e8 100644 --- a/src/X509/CertificationRequest/CertificationRequest.php +++ b/src/X509/CertificationRequest/CertificationRequest.php @@ -21,19 +21,10 @@ */ final class CertificationRequest implements Stringable { - public function __construct( - /** - * Certification request info. - */ - protected CertificationRequestInfo $_certificationRequestInfo, - /** - * Signature algorithm. - */ - protected SignatureAlgorithmIdentifier $_signatureAlgorithm, - /** - * Signature. - */ - protected Signature $_signature + private function __construct( + private readonly CertificationRequestInfo $certificationRequestInfo, + private readonly SignatureAlgorithmIdentifier $signatureAlgorithm, + private readonly Signature $signature ) { } @@ -46,6 +37,14 @@ public function __toString(): string ->string(); } + public static function create( + CertificationRequestInfo $_certificationRequestInfo, + SignatureAlgorithmIdentifier $_signatureAlgorithm, + Signature $_signature + ): self { + return new self($_certificationRequestInfo, $_signatureAlgorithm, $_signature); + } + /** * Initialize from ASN.1. */ @@ -57,7 +56,7 @@ public static function fromASN1(Sequence $seq): self throw new UnexpectedValueException('Unsupported signature algorithm ' . $algo->oid() . '.'); } $signature = Signature::fromSignatureData($seq->at(2)->asBitString()->string(), $algo); - return new self($info, $algo, $signature); + return self::create($info, $algo, $signature); } /** @@ -84,7 +83,7 @@ public static function fromPEM(PEM $pem): self */ public function certificationRequestInfo(): CertificationRequestInfo { - return $this->_certificationRequestInfo; + return $this->certificationRequestInfo; } /** @@ -92,12 +91,12 @@ public function certificationRequestInfo(): CertificationRequestInfo */ public function signatureAlgorithm(): SignatureAlgorithmIdentifier { - return $this->_signatureAlgorithm; + return $this->signatureAlgorithm; } public function signature(): Signature { - return $this->_signature; + return $this->signature; } /** @@ -106,9 +105,9 @@ public function signature(): Signature public function toASN1(): Sequence { return Sequence::create( - $this->_certificationRequestInfo->toASN1(), - $this->_signatureAlgorithm->toASN1(), - $this->_signature->bitString() + $this->certificationRequestInfo->toASN1(), + $this->signatureAlgorithm->toASN1(), + $this->signature->bitString() ); } @@ -139,9 +138,9 @@ public function toPEM(): PEM public function verify(?Crypto $crypto = null): bool { $crypto ??= Crypto::getDefault(); - $data = $this->_certificationRequestInfo->toASN1() + $data = $this->certificationRequestInfo->toASN1() ->toDER(); - $pk_info = $this->_certificationRequestInfo->subjectPKInfo(); - return $crypto->verify($data, $this->_signature, $pk_info, $this->_signatureAlgorithm); + $pk_info = $this->certificationRequestInfo->subjectPKInfo(); + return $crypto->verify($data, $this->signature, $pk_info, $this->signatureAlgorithm); } } diff --git a/src/X509/CertificationRequest/CertificationRequestInfo.php b/src/X509/CertificationRequest/CertificationRequestInfo.php index 4c5392d0..b93584e2 100644 --- a/src/X509/CertificationRequest/CertificationRequestInfo.php +++ b/src/X509/CertificationRequest/CertificationRequestInfo.php @@ -31,22 +31,27 @@ final class CertificationRequestInfo /** * Version. */ - private readonly int $_version; + private readonly int $version; /** * Attributes. */ - private ?Attributes $_attributes = null; + private ?Attributes $attributes = null; /** - * @param Name $_subject Subject - * @param PublicKeyInfo $_subjectPKInfo Public key info + * @param Name $subject Subject + * @param PublicKeyInfo $subjectPKInfo Public key info */ - public function __construct( - protected Name $_subject, - protected PublicKeyInfo $_subjectPKInfo + private function __construct( + private Name $subject, + private readonly PublicKeyInfo $subjectPKInfo ) { - $this->_version = self::VERSION_1; + $this->version = self::VERSION_1; + } + + public static function create(Name $subject, PublicKeyInfo $subjectPKInfo): self + { + return new self($subject, $subjectPKInfo); } /** @@ -62,16 +67,19 @@ public static function fromASN1(Sequence $seq): self } $subject = Name::fromASN1($seq->at(1)->asSequence()); $pkinfo = PublicKeyInfo::fromASN1($seq->at(2)->asSequence()); - $obj = new self($subject, $pkinfo); + $obj = self::create($subject, $pkinfo); if ($seq->hasTagged(0)) { - $obj->_attributes = Attributes::fromASN1($seq->getTagged(0)->asImplicit(Element::TYPE_SET)->asSet()); + $obj = $obj->withAttributes( + Attributes::fromASN1($seq->getTagged(0)->asImplicit(Element::TYPE_SET)->asSet()) + ); } + return $obj; } public function version(): int { - return $this->_version; + return $this->version; } /** @@ -80,13 +88,13 @@ public function version(): int public function withSubject(Name $subject): self { $obj = clone $this; - $obj->_subject = $subject; + $obj->subject = $subject; return $obj; } public function subject(): Name { - return $this->_subject; + return $this->subject; } /** @@ -94,7 +102,7 @@ public function subject(): Name */ public function subjectPKInfo(): PublicKeyInfo { - return $this->_subjectPKInfo; + return $this->subjectPKInfo; } /** @@ -102,7 +110,7 @@ public function subjectPKInfo(): PublicKeyInfo */ public function hasAttributes(): bool { - return isset($this->_attributes); + return isset($this->attributes); } public function attributes(): Attributes @@ -110,7 +118,7 @@ public function attributes(): Attributes if (! $this->hasAttributes()) { throw new LogicException('No attributes.'); } - return $this->_attributes; + return $this->attributes; } /** @@ -119,7 +127,7 @@ public function attributes(): Attributes public function withAttributes(Attributes $attribs): self { $obj = clone $this; - $obj->_attributes = $attribs; + $obj->attributes = $attribs; return $obj; } @@ -131,11 +139,11 @@ public function withAttributes(Attributes $attribs): self public function withExtensionRequest(Extensions $extensions): self { $obj = clone $this; - if (! isset($obj->_attributes)) { - $obj->_attributes = Attributes::create(); + if (! isset($obj->attributes)) { + $obj->attributes = Attributes::create(); } - $obj->_attributes = $obj->_attributes->withUnique( - Attribute::fromAttributeValues(new ExtensionRequestValue($extensions)) + $obj->attributes = $obj->attributes->withUnique( + Attribute::fromAttributeValues(ExtensionRequestValue::create($extensions)) ); return $obj; } @@ -145,9 +153,9 @@ public function withExtensionRequest(Extensions $extensions): self */ public function toASN1(): Sequence { - $elements = [Integer::create($this->_version), $this->_subject->toASN1(), $this->_subjectPKInfo->toASN1()]; - if (isset($this->_attributes)) { - $elements[] = ImplicitlyTaggedType::create(0, $this->_attributes->toASN1()); + $elements = [Integer::create($this->version), $this->subject->toASN1(), $this->subjectPKInfo->toASN1()]; + if (isset($this->attributes)) { + $elements[] = ImplicitlyTaggedType::create(0, $this->attributes->toASN1()); } return Sequence::create(...$elements); } @@ -168,6 +176,6 @@ public function sign( $data = $this->toASN1() ->toDER(); $signature = $crypto->sign($data, $privkey_info, $algo); - return new CertificationRequest($this, $algo, $signature); + return CertificationRequest::create($this, $algo, $signature); } } diff --git a/src/X509/Feature/DateTimeHelper.php b/src/X509/Feature/DateTimeHelper.php index 89e37551..5b872ce1 100644 --- a/src/X509/Feature/DateTimeHelper.php +++ b/src/X509/Feature/DateTimeHelper.php @@ -21,7 +21,7 @@ trait DateTimeHelper * @param null|string $time Time string, default to 'now' * @param null|string $tz Timezone, default if omitted */ - private static function _createDateTime(?string $time = null, ?string $tz = null): DateTimeImmutable + private static function createDateTime(?string $time = null, ?string $tz = null): DateTimeImmutable { if (! isset($time)) { $time = 'now'; @@ -30,8 +30,8 @@ private static function _createDateTime(?string $time = null, ?string $tz = null $tz = date_default_timezone_get(); } try { - $dt = new DateTimeImmutable($time, self::_createTimeZone($tz)); - return self::_roundDownFractionalSeconds($dt); + $dt = new DateTimeImmutable($time, self::createTimeZone($tz)); + return self::roundDownFractionalSeconds($dt); } catch (Exception $e) { throw new RuntimeException('Failed to create DateTime:', 0, $e); } @@ -40,7 +40,7 @@ private static function _createDateTime(?string $time = null, ?string $tz = null /** * Rounds a \DateTimeImmutable value such that fractional seconds are removed. */ - private static function _roundDownFractionalSeconds(DateTimeImmutable $dt): DateTimeImmutable + private static function roundDownFractionalSeconds(DateTimeImmutable $dt): DateTimeImmutable { return DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $dt->format('Y-m-d H:i:s'), $dt->getTimezone()); } @@ -48,7 +48,7 @@ private static function _roundDownFractionalSeconds(DateTimeImmutable $dt): Date /** * Create DateTimeZone object from string. */ - private static function _createTimeZone(string $tz): DateTimeZone + private static function createTimeZone(string $tz): DateTimeZone { try { return new DateTimeZone($tz); diff --git a/src/X509/GeneralName/IPAddress.php b/src/X509/GeneralName/IPAddress.php index 4ff37ea7..ba55f527 100644 --- a/src/X509/GeneralName/IPAddress.php +++ b/src/X509/GeneralName/IPAddress.php @@ -21,7 +21,7 @@ */ abstract class IPAddress extends GeneralName { - public function __construct( + protected function __construct( protected string $ip, protected ?string $mask = null ) { diff --git a/tests/ASN1/ElementTest.php b/tests/ASN1/ElementTest.php index 8691d1b4..f470f609 100644 --- a/tests/ASN1/ElementTest.php +++ b/tests/ASN1/ElementTest.php @@ -5,7 +5,6 @@ namespace SpomkyLabs\Pki\Test\ASN1; use PHPUnit\Framework\TestCase; -use ReflectionClass; use SpomkyLabs\Pki\ASN1\Element; use SpomkyLabs\Pki\ASN1\Type\Primitive\NullType; use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType; @@ -18,7 +17,7 @@ final class ElementTest extends TestCase /** * @test */ - public function unknownTagToName() + public function unknownTagToName(): void { static::assertEquals('TAG 100', Element::tagToName(100)); } @@ -26,20 +25,7 @@ public function unknownTagToName() /** * @test */ - public function isTypeUniversalInvalidClass() - { - $el = NullType::create(); - $cls = new ReflectionClass($el); - $prop = $cls->getProperty('typeTag'); - $prop->setAccessible(true); - $prop->setValue($el, Element::TYPE_BOOLEAN); - static::assertFalse($el->isType(Element::TYPE_BOOLEAN)); - } - - /** - * @test - */ - public function isPseudotypeFail() + public function isPseudotypeFail(): void { $el = NullType::create(); static::assertFalse($el->isType(-99)); @@ -48,7 +34,7 @@ public function isPseudotypeFail() /** * @test */ - public function asElement() + public function asElement(): NullType { $el = NullType::create(); static::assertEquals($el, $el->asElement()); @@ -60,7 +46,7 @@ public function asElement() * * @test */ - public function asUnspecified(Element $el) + public function asUnspecified(Element $el): void { $type = $el->asUnspecified(); static::assertInstanceOf(UnspecifiedType::class, $type); @@ -69,7 +55,7 @@ public function asUnspecified(Element $el) /** * @test */ - public function isIndefinite() + public function isIndefinite(): void { $el = Element::fromDER(hex2bin('308005000000'))->asElement(); static::assertTrue($el->hasIndefiniteLength()); @@ -78,7 +64,7 @@ public function isIndefinite() /** * @test */ - public function setDefinite() + public function setDefinite(): void { $el = Element::fromDER(hex2bin('308005000000'))->asElement(); $el = $el->withIndefiniteLength(false); diff --git a/tests/CryptoBridge/Unit/Crypto/OpenSSLCryptoTest.php b/tests/CryptoBridge/Unit/Crypto/OpenSSLCryptoTest.php index d096945f..230126cb 100644 --- a/tests/CryptoBridge/Unit/Crypto/OpenSSLCryptoTest.php +++ b/tests/CryptoBridge/Unit/Crypto/OpenSSLCryptoTest.php @@ -80,7 +80,7 @@ public static function tearDownAfterClass(): void * * @test */ - public function signAndVerifyRSA(SignatureAlgorithmIdentifier $algo) + public function signAndVerifyRSA(SignatureAlgorithmIdentifier $algo): void { $signature = self::$_crypto->sign(self::DATA, self::$_rsaPrivKeyInfo, $algo); static::assertInstanceOf(Signature::class, $signature); @@ -105,7 +105,7 @@ public function provideSignAndVerifyRSA(): iterable * * @test */ - public function signAndVerifyEC(SignatureAlgorithmIdentifier $algo) + public function signAndVerifyEC(SignatureAlgorithmIdentifier $algo): void { $signature = self::$_crypto->sign(self::DATA, self::$_ecPrivKeyInfo, $algo); static::assertInstanceOf(Signature::class, $signature); @@ -122,7 +122,7 @@ public function provideSignAndVerifyEC(): iterable /** * @test */ - public function unsupportedDigestFail() + public function unsupportedDigestFail(): void { $algo = MD2WithRSAEncryptionAlgorithmIdentifier::create(); $this->expectException(UnexpectedValueException::class); @@ -132,9 +132,9 @@ public function unsupportedDigestFail() /** * @test */ - public function signInvalidKeyFails() + public function signInvalidKeyFails(): void { - $pk = new RSAPrivateKey(0, 0, 0, 0, 0, 0, 0, 0); + $pk = RSAPrivateKey::create('0', '0', '0', '0', '0', '0', '0', '0'); $algo = SHA1WithRSAEncryptionAlgorithmIdentifier::create(); $this->expectException(RuntimeException::class); self::$_crypto->sign(self::DATA, $pk->privateKeyInfo(), $algo); @@ -143,7 +143,7 @@ public function signInvalidKeyFails() /** * @test */ - public function verifyInvalidKeyType() + public function verifyInvalidKeyType(): void { $signature = RSASignature::fromSignatureString(''); $algo = SHA1WithRSAEncryptionAlgorithmIdentifier::create(); @@ -160,7 +160,7 @@ public function verifyInvalidKeyType() * * @test */ - public function encryptAndDecrypt($data, CipherAlgorithmIdentifier $algo, $key) + public function encryptAndDecrypt($data, CipherAlgorithmIdentifier $algo, $key): void { $ciphertext = self::$_crypto->encrypt($data, $key, $algo); static::assertNotEquals($data, $ciphertext); @@ -192,7 +192,7 @@ public function provideEncryptAndDecrypt(): iterable /** * @test */ - public function unsupportedRC2KeySize() + public function unsupportedRC2KeySize(): void { $data = '12345678'; $key = '12345678'; @@ -204,7 +204,7 @@ public function unsupportedRC2KeySize() /** * @test */ - public function encryptUnalignedFail() + public function encryptUnalignedFail(): void { $data = '1234567'; $key = '12345678'; @@ -216,7 +216,7 @@ public function encryptUnalignedFail() /** * @test */ - public function decryptUnalignedFail() + public function decryptUnalignedFail(): void { $data = '1234567'; $key = '12345678'; @@ -228,7 +228,7 @@ public function decryptUnalignedFail() /** * @test */ - public function unsupportedCipherFail() + public function unsupportedCipherFail(): void { $this->expectException(UnexpectedValueException::class); self::$_crypto->encrypt(self::DATA, '', new UnsupportedCipher()); @@ -237,7 +237,7 @@ public function unsupportedCipherFail() /** * @test */ - public function invalidRC2AlgoFail() + public function invalidRC2AlgoFail(): void { $this->expectException(UnexpectedValueException::class); self::$_crypto->encrypt(self::DATA, '', new InvalidRC2()); @@ -246,7 +246,7 @@ public function invalidRC2AlgoFail() /** * @test */ - public function unsupportedRC2KeySizeFail() + public function unsupportedRC2KeySizeFail(): void { $this->expectException(UnexpectedValueException::class); self::$_crypto->encrypt(self::DATA, 'x', RC2CBCAlgorithmIdentifier::create(8, '87654321')); @@ -257,7 +257,7 @@ public function unsupportedRC2KeySizeFail() * * @test */ - public function signatureMethod(PrivateKeyInfo $pki, SignatureAlgorithmIdentifier $algo) + public function signatureMethod(PrivateKeyInfo $pki, SignatureAlgorithmIdentifier $algo): void { $signature = self::$_crypto->sign(self::DATA, $pki, $algo); $result = self::$_crypto->verify(self::DATA, $signature, $pki->publicKeyInfo(), $algo); diff --git a/tests/CryptoTypes/Unit/AlgoId/Hash/MD5AITest.php b/tests/CryptoTypes/Unit/AlgoId/Hash/MD5AITest.php index 26b87a67..e3fd5411 100644 --- a/tests/CryptoTypes/Unit/AlgoId/Hash/MD5AITest.php +++ b/tests/CryptoTypes/Unit/AlgoId/Hash/MD5AITest.php @@ -21,7 +21,7 @@ final class MD5AITest extends TestCase */ public function encode() { - $ai = new MD5AlgorithmIdentifier(); + $ai = MD5AlgorithmIdentifier::create(); $seq = $ai->toASN1(); static::assertInstanceOf(Sequence::class, $seq); return $seq; diff --git a/tests/CryptoTypes/Unit/AlgoId/Hash/SHA1AITest.php b/tests/CryptoTypes/Unit/AlgoId/Hash/SHA1AITest.php index 2254b6cb..98b206a2 100644 --- a/tests/CryptoTypes/Unit/AlgoId/Hash/SHA1AITest.php +++ b/tests/CryptoTypes/Unit/AlgoId/Hash/SHA1AITest.php @@ -22,7 +22,7 @@ final class SHA1AITest extends TestCase */ public function encode() { - $ai = new SHA1AlgorithmIdentifier(); + $ai = SHA1AlgorithmIdentifier::create(); $seq = $ai->toASN1(); static::assertInstanceOf(Sequence::class, $seq); return $seq; diff --git a/tests/CryptoTypes/Unit/AlgoId/Signature/SHA1WithRSAAITest.php b/tests/CryptoTypes/Unit/AlgoId/Signature/SHA1WithRSAAITest.php index 1f7aed94..1f8d27ff 100644 --- a/tests/CryptoTypes/Unit/AlgoId/Signature/SHA1WithRSAAITest.php +++ b/tests/CryptoTypes/Unit/AlgoId/Signature/SHA1WithRSAAITest.php @@ -16,11 +16,9 @@ final class SHA1WithRSAAITest extends TestCase { /** - * @return Sequence - * * @test */ - public function encode() + public function encode(): Sequence { $ai = SHA1WithRSAEncryptionAlgorithmIdentifier::create(); $seq = $ai->toASN1(); @@ -33,7 +31,7 @@ public function encode() * * @test */ - public function decode(Sequence $seq) + public function decode(Sequence $seq): AlgorithmIdentifier|SHA1WithRSAEncryptionAlgorithmIdentifier { $ai = AlgorithmIdentifier::fromASN1($seq); static::assertInstanceOf(SHA1WithRSAEncryptionAlgorithmIdentifier::class, $ai); @@ -45,7 +43,7 @@ public function decode(Sequence $seq) * * @test */ - public function decodeNoParamsFail(Sequence $seq) + public function decodeNoParamsFail(Sequence $seq): void { $seq = $seq->withoutElement(1); $this->expectException(UnexpectedValueException::class); @@ -57,7 +55,7 @@ public function decodeNoParamsFail(Sequence $seq) * * @test */ - public function decodeInvalidParamsFail(Sequence $seq) + public function decodeInvalidParamsFail(Sequence $seq): void { $seq = $seq->withReplaced(1, Sequence::create()); $this->expectException(UnexpectedValueException::class); @@ -69,7 +67,7 @@ public function decodeInvalidParamsFail(Sequence $seq) * * @test */ - public function name(AlgorithmIdentifier $algo) + public function name(AlgorithmIdentifier $algo): void { static::assertIsString($algo->name()); } diff --git a/tests/CryptoTypes/Unit/EC/ECPrivateKeyTest.php b/tests/CryptoTypes/Unit/EC/ECPrivateKeyTest.php index 671e651f..c7507141 100644 --- a/tests/CryptoTypes/Unit/EC/ECPrivateKeyTest.php +++ b/tests/CryptoTypes/Unit/EC/ECPrivateKeyTest.php @@ -169,7 +169,7 @@ public function namedCurveNotSet(ECPrivateKey $pk) */ public function publicKeyNotSet() { - $pk = new ECPrivateKey("\0"); + $pk = ECPrivateKey::create("\0"); $this->expectException(LogicException::class); $pk->publicKey(); } diff --git a/tests/CryptoTypes/Unit/EC/ECPublicKeyTest.php b/tests/CryptoTypes/Unit/EC/ECPublicKeyTest.php index bc6e8f28..c4991007 100644 --- a/tests/CryptoTypes/Unit/EC/ECPublicKeyTest.php +++ b/tests/CryptoTypes/Unit/EC/ECPublicKeyTest.php @@ -58,7 +58,7 @@ public function publicKeyInfo(ECPublicKey $pk) */ public function noNamedCurve() { - $pk = new ECPublicKey("\x04\0\0"); + $pk = ECPublicKey::create("\x04\0\0"); $this->expectException(LogicException::class); $pk->publicKeyInfo(); } @@ -69,7 +69,7 @@ public function noNamedCurve() public function invalidECPoint() { $this->expectException(InvalidArgumentException::class); - new ECPublicKey("\x0"); + ECPublicKey::create("\x0"); } /** @@ -139,7 +139,7 @@ public function namedCurve(ECPublicKey $pk) */ public function noCurveFail() { - $pk = new ECPublicKey("\x4\0\0"); + $pk = ECPublicKey::create("\x4\0\0"); $this->expectException(LogicException::class); $pk->namedCurve(); } @@ -149,7 +149,7 @@ public function noCurveFail() */ public function compressedFail() { - $pk = new ECPublicKey("\x3\0"); + $pk = ECPublicKey::create("\x3\0"); $this->expectException(RuntimeException::class); $pk->curvePoint(); } diff --git a/tests/CryptoTypes/Unit/PublicKeyInfoTest.php b/tests/CryptoTypes/Unit/PublicKeyInfoTest.php index d13d11d9..5b1200fd 100644 --- a/tests/CryptoTypes/Unit/PublicKeyInfoTest.php +++ b/tests/CryptoTypes/Unit/PublicKeyInfoTest.php @@ -196,7 +196,7 @@ public function invalidAI(PublicKeyInfo $pki) */ public function invalidECAlgoFail() { - $pki = new PublicKeyInfo(new PubliceKeyInfoTest_InvalidECAlgo(), BitString::create('')); + $pki = PublicKeyInfo::create(new PubliceKeyInfoTest_InvalidECAlgo(), BitString::create('')); $this->expectException(UnexpectedValueException::class); $pki->publicKey(); } diff --git a/tests/CryptoTypes/Unit/RFC8410/Curve25519Test.php b/tests/CryptoTypes/Unit/RFC8410/Curve25519Test.php index 246e7c6e..c8811447 100644 --- a/tests/CryptoTypes/Unit/RFC8410/Curve25519Test.php +++ b/tests/CryptoTypes/Unit/RFC8410/Curve25519Test.php @@ -133,7 +133,7 @@ public function ed25519PubInvalidPublicKey() { $this->expectException(UnexpectedValueException::class); $this->expectExceptionMessageMatches('/public key/'); - new Ed25519PublicKey(''); + Ed25519PublicKey::create(''); } /** diff --git a/tests/CryptoTypes/Unit/RFC8410/Curve448Test.php b/tests/CryptoTypes/Unit/RFC8410/Curve448Test.php index cf79fcbf..8d184bbd 100644 --- a/tests/CryptoTypes/Unit/RFC8410/Curve448Test.php +++ b/tests/CryptoTypes/Unit/RFC8410/Curve448Test.php @@ -92,7 +92,7 @@ public function ed448PubInvalidPublicKey() { $this->expectException(UnexpectedValueException::class); $this->expectExceptionMessageMatches('/public key/'); - new Ed448PublicKey(''); + Ed448PublicKey::create(''); } /** @@ -188,7 +188,7 @@ public function x448PubInvalidPublicKey() { $this->expectException(UnexpectedValueException::class); $this->expectExceptionMessageMatches('/public key/'); - new X448PublicKey(''); + X448PublicKey::create(''); } /** diff --git a/tests/CryptoTypes/Unit/Signature/ECSignatureTest.php b/tests/CryptoTypes/Unit/Signature/ECSignatureTest.php index d7c15645..2ccb0e2c 100644 --- a/tests/CryptoTypes/Unit/Signature/ECSignatureTest.php +++ b/tests/CryptoTypes/Unit/Signature/ECSignatureTest.php @@ -15,13 +15,11 @@ final class ECSignatureTest extends TestCase { /** - * @return ECSignature - * * @test */ - public function create() + public function create(): ECSignature { - $sig = new ECSignature('123456789', '987654321'); + $sig = ECSignature::create('123456789', '987654321'); static::assertInstanceOf(ECSignature::class, $sig); return $sig; } @@ -31,7 +29,7 @@ public function create() * * @test */ - public function encode(ECSignature $sig) + public function encode(ECSignature $sig): void { $el = $sig->toASN1(); static::assertInstanceOf(Sequence::class, $el); @@ -42,7 +40,7 @@ public function encode(ECSignature $sig) * * @test */ - public function toDER(ECSignature $sig) + public function toDER(ECSignature $sig): string { $der = $sig->toDER(); static::assertIsString($der); @@ -56,7 +54,7 @@ public function toDER(ECSignature $sig) * * @test */ - public function decode($data) + public function decode($data): ECSignature { $sig = ECSignature::fromDER($data); static::assertInstanceOf(ECSignature::class, $sig); @@ -69,7 +67,7 @@ public function decode($data) * * @test */ - public function recoded(ECSignature $ref, ECSignature $sig) + public function recoded(ECSignature $ref, ECSignature $sig): void { static::assertEquals($ref, $sig); } @@ -79,7 +77,7 @@ public function recoded(ECSignature $ref, ECSignature $sig) * * @test */ - public function rValue(ECSignature $sig) + public function rValue(ECSignature $sig): void { static::assertEquals('123456789', $sig->r()); } @@ -89,7 +87,7 @@ public function rValue(ECSignature $sig) * * @test */ - public function sValue(ECSignature $sig) + public function sValue(ECSignature $sig): void { static::assertEquals('987654321', $sig->s()); } @@ -99,7 +97,7 @@ public function sValue(ECSignature $sig) * * @test */ - public function bitString(ECSignature $sig) + public function bitString(ECSignature $sig): void { static::assertInstanceOf(BitString::class, $sig->bitString()); } diff --git a/tests/CryptoTypes/Unit/Signature/Ed25519SignatureTest.php b/tests/CryptoTypes/Unit/Signature/Ed25519SignatureTest.php index ff801c25..36f79d07 100644 --- a/tests/CryptoTypes/Unit/Signature/Ed25519SignatureTest.php +++ b/tests/CryptoTypes/Unit/Signature/Ed25519SignatureTest.php @@ -19,7 +19,7 @@ final class Ed25519SignatureTest extends TestCase */ public function create(): Ed25519Signature { - $sig = new Ed25519Signature(str_repeat("\0", 64)); + $sig = Ed25519Signature::create(str_repeat("\0", 64)); static::assertInstanceOf(Ed25519Signature::class, $sig); return $sig; } @@ -41,6 +41,6 @@ public function invalid() { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageMatches('/must be 64 octets/'); - new Ed25519Signature(''); + Ed25519Signature::create(''); } } diff --git a/tests/CryptoTypes/Unit/Signature/Ed448SignatureTest.php b/tests/CryptoTypes/Unit/Signature/Ed448SignatureTest.php index 0b37124a..a11f54f0 100644 --- a/tests/CryptoTypes/Unit/Signature/Ed448SignatureTest.php +++ b/tests/CryptoTypes/Unit/Signature/Ed448SignatureTest.php @@ -19,7 +19,7 @@ final class Ed448SignatureTest extends TestCase */ public function create(): Ed448Signature { - $sig = new Ed448Signature(str_repeat("\0", 114)); + $sig = Ed448Signature::create(str_repeat("\0", 114)); static::assertInstanceOf(Ed448Signature::class, $sig); return $sig; } @@ -29,7 +29,7 @@ public function create(): Ed448Signature * * @test */ - public function bitString(Ed448Signature $sig) + public function bitString(Ed448Signature $sig): void { static::assertInstanceOf(BitString::class, $sig->bitString()); } @@ -37,10 +37,10 @@ public function bitString(Ed448Signature $sig) /** * @test */ - public function invalid() + public function invalid(): void { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageMatches('/must be 114 octets/'); - new Ed448Signature(''); + Ed448Signature::create(''); } } diff --git a/tests/CryptoTypes/Unit/Signature/GenericSignatureTest.php b/tests/CryptoTypes/Unit/Signature/GenericSignatureTest.php index 9f523daf..2c1ae4c1 100644 --- a/tests/CryptoTypes/Unit/Signature/GenericSignatureTest.php +++ b/tests/CryptoTypes/Unit/Signature/GenericSignatureTest.php @@ -16,13 +16,11 @@ final class GenericSignatureTest extends TestCase { /** - * @return GenericSignature - * * @test */ - public function create() + public function create(): GenericSignature { - $sig = new GenericSignature(BitString::create('test'), SHA1WithRSAEncryptionAlgorithmIdentifier::create()); + $sig = GenericSignature::create(BitString::create('test'), SHA1WithRSAEncryptionAlgorithmIdentifier::create()); static::assertInstanceOf(GenericSignature::class, $sig); return $sig; } diff --git a/tests/X501/Unit/ASN1/RDNTest.php b/tests/X501/Unit/ASN1/RDNTest.php index 2a6bf6b8..5b145795 100644 --- a/tests/X501/Unit/ASN1/RDNTest.php +++ b/tests/X501/Unit/ASN1/RDNTest.php @@ -156,6 +156,6 @@ public function createFail() { $this->expectException(UnexpectedValueException::class); $this->expectExceptionMessage('RDN must have at least one AttributeTypeAndValue'); - new RDN(); + RDN::create(); } } diff --git a/tests/X501/Unit/MatchingRule/CaseExactMatchTest.php b/tests/X501/Unit/MatchingRule/CaseExactMatchTest.php index 18377fbc..c4a7e45e 100644 --- a/tests/X501/Unit/MatchingRule/CaseExactMatchTest.php +++ b/tests/X501/Unit/MatchingRule/CaseExactMatchTest.php @@ -24,7 +24,7 @@ final class CaseExactMatchTest extends TestCase */ public function match($assertion, $value, $expected) { - $rule = new CaseExactMatch(Element::TYPE_UTF8_STRING); + $rule = CaseExactMatch::create(Element::TYPE_UTF8_STRING); static::assertEquals($expected, $rule->compare($assertion, $value)); } diff --git a/tests/X501/Unit/MatchingRule/CaseIgnoreMatchTest.php b/tests/X501/Unit/MatchingRule/CaseIgnoreMatchTest.php index d3f69d65..c4d28f7f 100644 --- a/tests/X501/Unit/MatchingRule/CaseIgnoreMatchTest.php +++ b/tests/X501/Unit/MatchingRule/CaseIgnoreMatchTest.php @@ -24,7 +24,7 @@ final class CaseIgnoreMatchTest extends TestCase */ public function match($assertion, $value, $expected) { - $rule = new CaseIgnoreMatch(Element::TYPE_UTF8_STRING); + $rule = CaseIgnoreMatch::create(Element::TYPE_UTF8_STRING); static::assertEquals($expected, $rule->compare($assertion, $value)); } diff --git a/tests/X501/Unit/StringPrep/MapStepTest.php b/tests/X501/Unit/StringPrep/MapStepTest.php index ca552dbd..bdc458e4 100644 --- a/tests/X501/Unit/StringPrep/MapStepTest.php +++ b/tests/X501/Unit/StringPrep/MapStepTest.php @@ -15,14 +15,11 @@ final class MapStepTest extends TestCase /** * @dataProvider provideApplyCaseFold * - * @param string $string - * @param string $expected - * * @test */ - public function applyCaseFold($string, $expected) + public function applyCaseFold(string $string, string $expected): void { - $step = new MapStep(true); + $step = MapStep::create(true); static::assertEquals($expected, $step->apply($string)); } diff --git a/tests/X509/Integration/Ac/HolderTest.php b/tests/X509/Integration/Ac/HolderTest.php index 7c01ee55..de8d4f33 100644 --- a/tests/X509/Integration/Ac/HolderTest.php +++ b/tests/X509/Integration/Ac/HolderTest.php @@ -44,7 +44,7 @@ public function identifiesPKCSimple() public function identifiesPKCByEntityName() { $gn = GeneralNames::create(DirectoryName::create(self::$_pkc->tbsCertificate()->subject())); - $holder = new Holder(null, $gn); + $holder = Holder::create(null, $gn); static::assertTrue($holder->identifiesPKC(self::$_pkc)); } @@ -54,7 +54,7 @@ public function identifiesPKCByEntityName() public function identifiesPKCByEntityNameSANDirectoryName() { $gn = GeneralNames::create(DirectoryName::fromDNString('o=ACME Alternative Ltd., c=FI, cn=alt.example.com')); - $holder = new Holder(null, $gn); + $holder = Holder::create(null, $gn); static::assertTrue($holder->identifiesPKC(self::$_pkc)); } @@ -63,7 +63,7 @@ public function identifiesPKCByEntityNameSANDirectoryName() */ public function identifiesPKCNoIdentifiers() { - $holder = new Holder(); + $holder = Holder::create(); static::assertFalse($holder->identifiesPKC(self::$_pkc)); } @@ -72,8 +72,8 @@ public function identifiesPKCNoIdentifiers() */ public function identifiesPKCNoCertIdMatch() { - $is = new IssuerSerial(GeneralNames::create(DirectoryName::fromDNString('cn=Fail')), 1); - $holder = new Holder($is); + $is = IssuerSerial::create(GeneralNames::create(DirectoryName::fromDNString('cn=Fail')), '1'); + $holder = Holder::create($is); static::assertFalse($holder->identifiesPKC(self::$_pkc)); } @@ -83,7 +83,7 @@ public function identifiesPKCNoCertIdMatch() public function identifiesPKCNoEntityNameMatch() { $gn = GeneralNames::create(DirectoryName::fromDNString('cn=Fail')); - $holder = new Holder(null, $gn); + $holder = Holder::create(null, $gn); static::assertFalse($holder->identifiesPKC(self::$_pkc)); } } diff --git a/tests/X509/Integration/Ac/IssuerSerialTest.php b/tests/X509/Integration/Ac/IssuerSerialTest.php index d9a70a4f..0e29f7d5 100644 --- a/tests/X509/Integration/Ac/IssuerSerialTest.php +++ b/tests/X509/Integration/Ac/IssuerSerialTest.php @@ -73,9 +73,9 @@ public function serial(IssuerSerial $is) */ public function identifiesPKCSerialMismatch() { - $is = new IssuerSerial(GeneralNames::create( + $is = IssuerSerial::create(GeneralNames::create( DirectoryName::create(self::$_cert->tbsCertificate()->issuer()) - ), 1); + ), '1'); static::assertFalse($is->identifiesPKC(self::$_cert)); } @@ -84,7 +84,7 @@ public function identifiesPKCSerialMismatch() */ public function identifiesPKCWithIssuerUID() { - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString('cn=Sub'), self::$_privKey->publicKeyInfo(), Name::fromString('cn=Iss'), @@ -102,7 +102,7 @@ public function identifiesPKCWithIssuerUID() public function identifiesPKCIssuerUIDMismatch() { $issuer = Name::fromString('cn=Iss'); - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString('cn=Sub'), self::$_privKey->publicKeyInfo(), $issuer, @@ -110,7 +110,7 @@ public function identifiesPKCIssuerUIDMismatch() ); $tbs = $tbs->withIssuerUniqueID(UniqueIdentifier::fromString('uid')); $cert = $tbs->sign(SHA256WithRSAEncryptionAlgorithmIdentifier::create(), self::$_privKey); - $is = new IssuerSerial( + $is = IssuerSerial::create( GeneralNames::create(DirectoryName::create($issuer)), $cert->tbsCertificate() ->serialNumber(), @@ -124,7 +124,7 @@ public function identifiesPKCIssuerUIDMismatch() */ public function identifiesPKCNoUID() { - $is = new IssuerSerial( + $is = IssuerSerial::create( GeneralNames::create(DirectoryName::create(self::$_cert->tbsCertificate()->issuer())), self::$_cert->tbsCertificate()->serialNumber(), UniqueIdentifier::fromString('uid') diff --git a/tests/X509/Integration/AcValidation/InvalidBasicConstraintsTest.php b/tests/X509/Integration/AcValidation/InvalidBasicConstraintsTest.php index e8b43563..4537dea9 100644 --- a/tests/X509/Integration/AcValidation/InvalidBasicConstraintsTest.php +++ b/tests/X509/Integration/AcValidation/InvalidBasicConstraintsTest.php @@ -13,6 +13,7 @@ use SpomkyLabs\Pki\X501\ASN1\Name; use SpomkyLabs\Pki\X509\AttributeCertificate\AttCertIssuer; use SpomkyLabs\Pki\X509\AttributeCertificate\AttCertValidityPeriod; +use SpomkyLabs\Pki\X509\AttributeCertificate\AttributeCertificate as AttributeCertificateAlias; use SpomkyLabs\Pki\X509\AttributeCertificate\AttributeCertificateInfo; use SpomkyLabs\Pki\X509\AttributeCertificate\Attributes; use SpomkyLabs\Pki\X509\AttributeCertificate\Holder; @@ -32,11 +33,11 @@ */ final class InvalidBasicConstraintsTest extends TestCase { - private static $_holderPath; + private static ?CertificationPath $_holderPath; - private static $_issuerPath; + private static ?CertificationPath $_issuerPath; - private static $_ac; + private static ?AttributeCertificateAlias $_ac; public static function setUpBeforeClass(): void { @@ -49,21 +50,21 @@ public static function setUpBeforeClass(): void $issuer_ca_pk = PrivateKeyInfo::fromPEM(PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-interm-ec.pem')); $issuer_pk = PrivateKeyInfo::fromPEM(PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-ec.pem')); // create issuer certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString('cn=AC CA'), $issuer_pk->publicKeyInfo(), - new Name(), + Name::create(), Validity::fromStrings('now', 'now + 1 hour') ); $tbs = $tbs->withIssuerCertificate($issuer_ca); $tbs = $tbs->withAdditionalExtensions( - new KeyUsageExtension(true, KeyUsageExtension::DIGITAL_SIGNATURE), - new BasicConstraintsExtension(true, true) + KeyUsageExtension::create(true, KeyUsageExtension::DIGITAL_SIGNATURE), + BasicConstraintsExtension::create(true, true) ); $issuer = $tbs->sign(ECDSAWithSHA512AlgorithmIdentifier::create(), $issuer_ca_pk); self::$_holderPath = CertificationPath::fromTrustAnchorToTarget($root_ca, $holder, $interms); self::$_issuerPath = CertificationPath::fromTrustAnchorToTarget($root_ca, $issuer, $interms); - $aci = new AttributeCertificateInfo( + $aci = AttributeCertificateInfo::create( Holder::fromPKC($holder), AttCertIssuer::fromPKC($issuer), AttCertValidityPeriod::fromStrings('now', 'now + 1 hour'), @@ -84,8 +85,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $config = new ACValidationConfig(self::$_holderPath, self::$_issuerPath); - $validator = new ACValidator(self::$_ac, $config); + $config = ACValidationConfig::create(self::$_holderPath, self::$_issuerPath); + $validator = ACValidator::create(self::$_ac, $config); $this->expectException(X509ValidationException::class); $validator->validate(); } diff --git a/tests/X509/Integration/AcValidation/InvalidHolderNameTest.php b/tests/X509/Integration/AcValidation/InvalidHolderNameTest.php index 01a97b57..a0240b14 100644 --- a/tests/X509/Integration/AcValidation/InvalidHolderNameTest.php +++ b/tests/X509/Integration/AcValidation/InvalidHolderNameTest.php @@ -46,8 +46,8 @@ public static function setUpBeforeClass(): void $issuer_pk = PrivateKeyInfo::fromPEM(PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-ec.pem')); self::$_holderPath = CertificationPath::fromTrustAnchorToTarget($root_ca, $holder, $interms); self::$_issuerPath = CertificationPath::fromTrustAnchorToTarget($root_ca, $issuer, $interms); - $aci = new AttributeCertificateInfo( - new Holder(new IssuerSerial(GeneralNames::create(DirectoryName::fromDNString('cn=Test')), 1)), + $aci = AttributeCertificateInfo::create( + Holder::create(IssuerSerial::create(GeneralNames::create(DirectoryName::fromDNString('cn=Test')), '1')), AttCertIssuer::fromPKC($issuer), AttCertValidityPeriod::fromStrings('now', 'now + 1 hour'), Attributes::create() @@ -67,8 +67,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $config = new ACValidationConfig(self::$_holderPath, self::$_issuerPath); - $validator = new ACValidator(self::$_ac, $config); + $config = ACValidationConfig::create(self::$_holderPath, self::$_issuerPath); + $validator = ACValidator::create(self::$_ac, $config); $this->expectException(X509ValidationException::class); $validator->validate(); } diff --git a/tests/X509/Integration/AcValidation/InvalidHolderPathTest.php b/tests/X509/Integration/AcValidation/InvalidHolderPathTest.php index 3ce2a883..3ebc35fb 100644 --- a/tests/X509/Integration/AcValidation/InvalidHolderPathTest.php +++ b/tests/X509/Integration/AcValidation/InvalidHolderPathTest.php @@ -42,9 +42,9 @@ public static function setUpBeforeClass(): void $issuer = Certificate::fromPEM(PEM::fromFile(TEST_ASSETS_DIR . '/certs/acme-ecdsa.pem')); $issuer_pk = PrivateKeyInfo::fromPEM(PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-ec.pem')); // intentionally missing intermediate certificate - self::$_holderPath = new CertificationPath($root_ca, $holder); + self::$_holderPath = CertificationPath::create($root_ca, $holder); self::$_issuerPath = CertificationPath::fromTrustAnchorToTarget($root_ca, $issuer, $interms); - $aci = new AttributeCertificateInfo( + $aci = AttributeCertificateInfo::create( Holder::fromPKC($holder), AttCertIssuer::fromPKC($issuer), AttCertValidityPeriod::fromStrings('now', 'now + 1 hour'), @@ -65,8 +65,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $config = new ACValidationConfig(self::$_holderPath, self::$_issuerPath); - $validator = new ACValidator(self::$_ac, $config); + $config = ACValidationConfig::create(self::$_holderPath, self::$_issuerPath); + $validator = ACValidator::create(self::$_ac, $config); $this->expectException(X509ValidationException::class); $validator->validate(); } diff --git a/tests/X509/Integration/AcValidation/InvalidIssuerNameTest.php b/tests/X509/Integration/AcValidation/InvalidIssuerNameTest.php index a4933465..67ab3fdb 100644 --- a/tests/X509/Integration/AcValidation/InvalidIssuerNameTest.php +++ b/tests/X509/Integration/AcValidation/InvalidIssuerNameTest.php @@ -44,7 +44,7 @@ public static function setUpBeforeClass(): void $issuer_pk = PrivateKeyInfo::fromPEM(PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-ec.pem')); self::$_holderPath = CertificationPath::fromTrustAnchorToTarget($root_ca, $holder, $interms); self::$_issuerPath = CertificationPath::fromTrustAnchorToTarget($root_ca, $issuer, $interms); - $aci = new AttributeCertificateInfo( + $aci = AttributeCertificateInfo::create( Holder::fromPKC($holder), AttCertIssuer::fromName(Name::fromString('cn=Nope')), AttCertValidityPeriod::fromStrings('now', 'now + 1 hour'), @@ -65,8 +65,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $config = new ACValidationConfig(self::$_holderPath, self::$_issuerPath); - $validator = new ACValidator(self::$_ac, $config); + $config = ACValidationConfig::create(self::$_holderPath, self::$_issuerPath); + $validator = ACValidator::create(self::$_ac, $config); $this->expectException(X509ValidationException::class); $validator->validate(); } diff --git a/tests/X509/Integration/AcValidation/InvalidIssuerPathTest.php b/tests/X509/Integration/AcValidation/InvalidIssuerPathTest.php index ce20be10..22f61e92 100644 --- a/tests/X509/Integration/AcValidation/InvalidIssuerPathTest.php +++ b/tests/X509/Integration/AcValidation/InvalidIssuerPathTest.php @@ -43,8 +43,8 @@ public static function setUpBeforeClass(): void $issuer_pk = PrivateKeyInfo::fromPEM(PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-ec.pem')); self::$_holderPath = CertificationPath::fromTrustAnchorToTarget($root_ca, $holder, $interms); // intentionally missing intermediate certificate - self::$_issuerPath = new CertificationPath($root_ca, $issuer); - $aci = new AttributeCertificateInfo( + self::$_issuerPath = CertificationPath::create($root_ca, $issuer); + $aci = AttributeCertificateInfo::create( Holder::fromPKC($holder), AttCertIssuer::fromPKC($issuer), AttCertValidityPeriod::fromStrings('now', 'now + 1 hour'), @@ -65,8 +65,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $config = new ACValidationConfig(self::$_holderPath, self::$_issuerPath); - $validator = new ACValidator(self::$_ac, $config); + $config = ACValidationConfig::create(self::$_holderPath, self::$_issuerPath); + $validator = ACValidator::create(self::$_ac, $config); $this->expectException(X509ValidationException::class); $validator->validate(); } diff --git a/tests/X509/Integration/AcValidation/InvalidKeyUsageTest.php b/tests/X509/Integration/AcValidation/InvalidKeyUsageTest.php index 2153d0e4..248b53f2 100644 --- a/tests/X509/Integration/AcValidation/InvalidKeyUsageTest.php +++ b/tests/X509/Integration/AcValidation/InvalidKeyUsageTest.php @@ -48,18 +48,18 @@ public static function setUpBeforeClass(): void $issuer_ca_pk = PrivateKeyInfo::fromPEM(PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-interm-ec.pem')); $issuer_pk = PrivateKeyInfo::fromPEM(PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-ec.pem')); // create issuer certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString('cn=AC CA'), $issuer_pk->publicKeyInfo(), - new Name(), + Name::create(), Validity::fromStrings('now', 'now + 1 hour') ); $tbs = $tbs->withIssuerCertificate($issuer_ca); - $tbs = $tbs->withAdditionalExtensions(new KeyUsageExtension(true, 0)); + $tbs = $tbs->withAdditionalExtensions(KeyUsageExtension::create(true, 0)); $issuer = $tbs->sign(ECDSAWithSHA512AlgorithmIdentifier::create(), $issuer_ca_pk); self::$_holderPath = CertificationPath::fromTrustAnchorToTarget($root_ca, $holder, $interms); self::$_issuerPath = CertificationPath::fromTrustAnchorToTarget($root_ca, $issuer, $interms); - $aci = new AttributeCertificateInfo( + $aci = AttributeCertificateInfo::create( Holder::fromPKC($holder), AttCertIssuer::fromPKC($issuer), AttCertValidityPeriod::fromStrings('now', 'now + 1 hour'), @@ -80,8 +80,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $config = new ACValidationConfig(self::$_holderPath, self::$_issuerPath); - $validator = new ACValidator(self::$_ac, $config); + $config = ACValidationConfig::create(self::$_holderPath, self::$_issuerPath); + $validator = ACValidator::create(self::$_ac, $config); $this->expectException(X509ValidationException::class); $validator->validate(); } diff --git a/tests/X509/Integration/AcValidation/InvalidSignatureTest.php b/tests/X509/Integration/AcValidation/InvalidSignatureTest.php index b030b185..c48ead0f 100644 --- a/tests/X509/Integration/AcValidation/InvalidSignatureTest.php +++ b/tests/X509/Integration/AcValidation/InvalidSignatureTest.php @@ -44,7 +44,7 @@ public static function setUpBeforeClass(): void $issuer_pk = PrivateKeyInfo::fromPEM(PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-interm-ec.pem')); self::$_holderPath = CertificationPath::fromTrustAnchorToTarget($root_ca, $holder, $interms); self::$_issuerPath = CertificationPath::fromTrustAnchorToTarget($root_ca, $issuer, $interms); - $aci = new AttributeCertificateInfo( + $aci = AttributeCertificateInfo::create( Holder::fromPKC($holder), AttCertIssuer::fromPKC($issuer), AttCertValidityPeriod::fromStrings('now', 'now + 1 hour'), @@ -65,8 +65,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $config = new ACValidationConfig(self::$_holderPath, self::$_issuerPath); - $validator = new ACValidator(self::$_ac, $config); + $config = ACValidationConfig::create(self::$_holderPath, self::$_issuerPath); + $validator = ACValidator::create(self::$_ac, $config); $this->expectException(X509ValidationException::class); $validator->validate(); } diff --git a/tests/X509/Integration/AcValidation/NoTargetingTest.php b/tests/X509/Integration/AcValidation/NoTargetingTest.php index 16c119b0..fbaf632d 100644 --- a/tests/X509/Integration/AcValidation/NoTargetingTest.php +++ b/tests/X509/Integration/AcValidation/NoTargetingTest.php @@ -45,7 +45,7 @@ public static function setUpBeforeClass(): void $issuer_pk = PrivateKeyInfo::fromPEM(PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-ec.pem')); self::$_holderPath = CertificationPath::fromTrustAnchorToTarget($root_ca, $holder, $interms); self::$_issuerPath = CertificationPath::fromTrustAnchorToTarget($root_ca, $issuer, $interms); - $aci = new AttributeCertificateInfo( + $aci = AttributeCertificateInfo::create( Holder::fromPKC($holder), AttCertIssuer::fromPKC($issuer), AttCertValidityPeriod::fromStrings('now', 'now + 1 hour'), @@ -66,9 +66,9 @@ public static function tearDownAfterClass(): void */ public function validate() { - $config = new ACValidationConfig(self::$_holderPath, self::$_issuerPath); - $config = $config->withTargets(new TargetName(DNSName::create('test'))); - $validator = new ACValidator(self::$_ac, $config); + $config = ACValidationConfig::create(self::$_holderPath, self::$_issuerPath); + $config = $config->withTargets(TargetName::create(DNSName::create('test'))); + $validator = ACValidator::create(self::$_ac, $config); static::assertInstanceOf(AttributeCertificate::class, $validator->validate()); } } diff --git a/tests/X509/Integration/AcValidation/PassingTest.php b/tests/X509/Integration/AcValidation/PassingTest.php index b3dc4934..bdcfa834 100644 --- a/tests/X509/Integration/AcValidation/PassingTest.php +++ b/tests/X509/Integration/AcValidation/PassingTest.php @@ -46,14 +46,14 @@ public static function setUpBeforeClass(): void $issuer_pk = PrivateKeyInfo::fromPEM(PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-ec.pem')); self::$_holderPath = CertificationPath::fromTrustAnchorToTarget($root_ca, $holder, $interms); self::$_issuerPath = CertificationPath::fromTrustAnchorToTarget($root_ca, $issuer, $interms); - $aci = new AttributeCertificateInfo( + $aci = AttributeCertificateInfo::create( Holder::fromPKC($holder), AttCertIssuer::fromPKC($issuer), AttCertValidityPeriod::fromStrings('now', 'now + 1 hour'), Attributes::create() ); $aci = $aci->withAdditionalExtensions( - TargetInformationExtension::fromTargets(new TargetName(DNSName::create('test'))) + TargetInformationExtension::fromTargets(TargetName::create(DNSName::create('test'))) ); self::$_ac = $aci->sign(ECDSAWithSHA256AlgorithmIdentifier::create(), $issuer_pk); } @@ -68,11 +68,11 @@ public static function tearDownAfterClass(): void /** * @test */ - public function validate() + public function validate(): void { - $config = new ACValidationConfig(self::$_holderPath, self::$_issuerPath); - $config = $config->withTargets(new TargetName(DNSName::create('test'))); - $validator = new ACValidator(self::$_ac, $config); + $config = ACValidationConfig::create(self::$_holderPath, self::$_issuerPath); + $config = $config->withTargets(TargetName::create(DNSName::create('test'))); + $validator = ACValidator::create(self::$_ac, $config); static::assertInstanceOf(AttributeCertificate::class, $validator->validate()); } } diff --git a/tests/X509/Integration/AcValidation/TargetMismatchTest.php b/tests/X509/Integration/AcValidation/TargetMismatchTest.php index c0c69602..a1145ff6 100644 --- a/tests/X509/Integration/AcValidation/TargetMismatchTest.php +++ b/tests/X509/Integration/AcValidation/TargetMismatchTest.php @@ -46,14 +46,14 @@ public static function setUpBeforeClass(): void $issuer_pk = PrivateKeyInfo::fromPEM(PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-ec.pem')); self::$_holderPath = CertificationPath::fromTrustAnchorToTarget($root_ca, $holder, $interms); self::$_issuerPath = CertificationPath::fromTrustAnchorToTarget($root_ca, $issuer, $interms); - $aci = new AttributeCertificateInfo( + $aci = AttributeCertificateInfo::create( Holder::fromPKC($holder), AttCertIssuer::fromPKC($issuer), AttCertValidityPeriod::fromStrings('now', 'now + 1 hour'), Attributes::create() ); $aci = $aci->withAdditionalExtensions( - TargetInformationExtension::fromTargets(new TargetName(DNSName::create('test'))) + TargetInformationExtension::fromTargets(TargetName::create(DNSName::create('test'))) ); self::$_ac = $aci->sign(ECDSAWithSHA256AlgorithmIdentifier::create(), $issuer_pk); } @@ -70,9 +70,9 @@ public static function tearDownAfterClass(): void */ public function validate() { - $config = new ACValidationConfig(self::$_holderPath, self::$_issuerPath); - $config = $config->withTargets(new TargetName(DNSName::create('nope'))); - $validator = new ACValidator(self::$_ac, $config); + $config = ACValidationConfig::create(self::$_holderPath, self::$_issuerPath); + $config = $config->withTargets(TargetName::create(DNSName::create('nope'))); + $validator = ACValidator::create(self::$_ac, $config); $this->expectException(X509ValidationException::class); $validator->validate(); } diff --git a/tests/X509/Integration/AcValidation/ValidityTest.php b/tests/X509/Integration/AcValidation/ValidityTest.php index adb0c560..d89fbee2 100644 --- a/tests/X509/Integration/AcValidation/ValidityTest.php +++ b/tests/X509/Integration/AcValidation/ValidityTest.php @@ -44,7 +44,7 @@ public static function setUpBeforeClass(): void $issuer_pk = PrivateKeyInfo::fromPEM(PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-ec.pem')); self::$_holderPath = CertificationPath::fromTrustAnchorToTarget($root_ca, $holder, $interms); self::$_issuerPath = CertificationPath::fromTrustAnchorToTarget($root_ca, $issuer, $interms); - $aci = new AttributeCertificateInfo( + $aci = AttributeCertificateInfo::create( Holder::fromPKC($holder), AttCertIssuer::fromPKC($issuer), AttCertValidityPeriod::fromStrings('now', 'now + 1 hour'), @@ -65,9 +65,9 @@ public static function tearDownAfterClass(): void */ public function validateBefore() { - $config = new ACValidationConfig(self::$_holderPath, self::$_issuerPath); + $config = ACValidationConfig::create(self::$_holderPath, self::$_issuerPath); $config = $config->withEvaluationTime(new DateTimeImmutable('now - 1 hour')); - $validator = new ACValidator(self::$_ac, $config); + $validator = ACValidator::create(self::$_ac, $config); $this->expectException(X509ValidationException::class); $validator->validate(); } @@ -77,9 +77,9 @@ public function validateBefore() */ public function validateAfter() { - $config = new ACValidationConfig(self::$_holderPath, self::$_issuerPath); + $config = ACValidationConfig::create(self::$_holderPath, self::$_issuerPath); $config = $config->withEvaluationTime(new DateTimeImmutable('now + 2 hours')); - $validator = new ACValidator(self::$_ac, $config); + $validator = ACValidator::create(self::$_ac, $config); $this->expectException(X509ValidationException::class); $validator->validate(); } diff --git a/tests/X509/Integration/PathValidation/BasicConstraintsMissingTest.php b/tests/X509/Integration/PathValidation/BasicConstraintsMissingTest.php index 21c1c191..6625a8f4 100644 --- a/tests/X509/Integration/PathValidation/BasicConstraintsMissingTest.php +++ b/tests/X509/Integration/PathValidation/BasicConstraintsMissingTest.php @@ -44,7 +44,7 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -53,7 +53,7 @@ public static function setUpBeforeClass(): void $tbs = $tbs->withVersion(TBSCertificate::VERSION_3); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -76,8 +76,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_cert); + $path = CertificationPath::create(self::$_ca, self::$_cert); $this->expectException(PathValidationException::class); - $path->validate(new PathValidationConfig(new DateTimeImmutable(), 3)); + $path->validate(PathValidationConfig::create(new DateTimeImmutable(), 3)); } } diff --git a/tests/X509/Integration/PathValidation/DifferentAlgoParamsTest.php b/tests/X509/Integration/PathValidation/DifferentAlgoParamsTest.php index 0adad5c3..daa7ae3f 100644 --- a/tests/X509/Integration/PathValidation/DifferentAlgoParamsTest.php +++ b/tests/X509/Integration/PathValidation/DifferentAlgoParamsTest.php @@ -6,9 +6,7 @@ use DateTimeImmutable; use PHPUnit\Framework\TestCase; -use ReflectionClass; use SpomkyLabs\Pki\CryptoEncoding\PEM; -use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Asymmetric\RSAEncryptionAlgorithmIdentifier; use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Signature\SHA1WithRSAEncryptionAlgorithmIdentifier; use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PrivateKey; use SpomkyLabs\Pki\X501\ASN1\Name; @@ -46,7 +44,7 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -56,11 +54,7 @@ public static function setUpBeforeClass(): void // create end-entity certificate $pubkey = self::$_certKey->publicKeyInfo(); // hack modified algorithm identifier into PublicKeyInfo - $cls = new ReflectionClass($pubkey); - $prop = $cls->getProperty('_algo'); - $prop->setAccessible(true); - $prop->setValue($pubkey, RSAEncryptionAlgorithmIdentifier::create()); - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), $pubkey, Name::fromString(self::CA_NAME), @@ -83,8 +77,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_cert); - $result = $path->validate(new PathValidationConfig(new DateTimeImmutable(), 3)); + $path = CertificationPath::create(self::$_ca, self::$_cert); + $result = $path->validate(PathValidationConfig::create(new DateTimeImmutable(), 3)); static::assertInstanceOf(PathValidationResult::class, $result); } } diff --git a/tests/X509/Integration/PathValidation/InhibitAnyPolicyTest.php b/tests/X509/Integration/PathValidation/InhibitAnyPolicyTest.php index 6d69fbaa..a18a5d6b 100644 --- a/tests/X509/Integration/PathValidation/InhibitAnyPolicyTest.php +++ b/tests/X509/Integration/PathValidation/InhibitAnyPolicyTest.php @@ -46,19 +46,19 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true, 1), - new InhibitAnyPolicyExtension(true, 0) + BasicConstraintsExtension::create(true, true, 1), + InhibitAnyPolicyExtension::create(true, 0) ); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -81,8 +81,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_cert); - $result = $path->validate(new PathValidationConfig(new DateTimeImmutable(), 3)); + $path = CertificationPath::create(self::$_ca, self::$_cert); + $result = $path->validate(PathValidationConfig::create(new DateTimeImmutable(), 3)); static::assertInstanceOf(PathValidationResult::class, $result); } } diff --git a/tests/X509/Integration/PathValidation/IntermediateTest.php b/tests/X509/Integration/PathValidation/IntermediateTest.php index f2a46838..765d65c8 100644 --- a/tests/X509/Integration/PathValidation/IntermediateTest.php +++ b/tests/X509/Integration/PathValidation/IntermediateTest.php @@ -53,29 +53,29 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true), - new KeyUsageExtension(true, KeyUsageExtension::KEY_CERT_SIGN) + BasicConstraintsExtension::create(true, true), + KeyUsageExtension::create(true, KeyUsageExtension::KEY_CERT_SIGN) ); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create intermediate certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::INTERM_NAME), self::$_intermKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); $tbs = $tbs->withIssuerCertificate(self::$_ca); - $tbs = $tbs->withAdditionalExtensions(new BasicConstraintsExtension(true, true)); + $tbs = $tbs->withAdditionalExtensions(BasicConstraintsExtension::create(true, true)); self::$_interm = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::INTERM_NAME), @@ -100,8 +100,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_interm, self::$_cert); - $result = $path->validate(new PathValidationConfig(new DateTimeImmutable(), 3)); + $path = CertificationPath::create(self::$_ca, self::$_interm, self::$_cert); + $result = $path->validate(PathValidationConfig::create(new DateTimeImmutable(), 3)); static::assertInstanceOf(PathValidationResult::class, $result); } } diff --git a/tests/X509/Integration/PathValidation/IssuerMismatchTest.php b/tests/X509/Integration/PathValidation/IssuerMismatchTest.php index a7c5a8c8..64616cfc 100644 --- a/tests/X509/Integration/PathValidation/IssuerMismatchTest.php +++ b/tests/X509/Integration/PathValidation/IssuerMismatchTest.php @@ -44,7 +44,7 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -52,7 +52,7 @@ public static function setUpBeforeClass(): void ); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString('cn=Someone else'), @@ -74,8 +74,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_cert); + $path = CertificationPath::create(self::$_ca, self::$_cert); $this->expectException(PathValidationException::class); - $path->validate(new PathValidationConfig(new DateTimeImmutable(), 3)); + $path->validate(PathValidationConfig::create(new DateTimeImmutable(), 3)); } } diff --git a/tests/X509/Integration/PathValidation/NameConstraintsTest.php b/tests/X509/Integration/PathValidation/NameConstraintsTest.php index 4fcffc69..472ac282 100644 --- a/tests/X509/Integration/PathValidation/NameConstraintsTest.php +++ b/tests/X509/Integration/PathValidation/NameConstraintsTest.php @@ -49,22 +49,22 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true, 1), - new NameConstraintsExtension( + BasicConstraintsExtension::create(true, true, 1), + NameConstraintsExtension::create( true, - new GeneralSubtrees(new GeneralSubtree(DirectoryName::fromDNString('c=FI'))) + GeneralSubtrees::create(GeneralSubtree::create(DirectoryName::fromDNString('c=FI'))) ) ); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -87,8 +87,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_cert); - $result = $path->validate(new PathValidationConfig(new DateTimeImmutable(), 3)); + $path = CertificationPath::create(self::$_ca, self::$_cert); + $result = $path->validate(PathValidationConfig::create(new DateTimeImmutable(), 3)); static::assertInstanceOf(PathValidationResult::class, $result); } } diff --git a/tests/X509/Integration/PathValidation/NoPoliciesTest.php b/tests/X509/Integration/PathValidation/NoPoliciesTest.php index f778ddac..ed8e2e8b 100644 --- a/tests/X509/Integration/PathValidation/NoPoliciesTest.php +++ b/tests/X509/Integration/PathValidation/NoPoliciesTest.php @@ -46,19 +46,19 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true), - new CertificatePoliciesExtension(false, new PolicyInformation('1.3.6.1.3.1')) + BasicConstraintsExtension::create(true, true), + CertificatePoliciesExtension::create(false, PolicyInformation::create('1.3.6.1.3.1')) ); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -66,7 +66,7 @@ public static function setUpBeforeClass(): void ); $tbs = $tbs->withIssuerCertificate(self::$_ca); $tbs = $tbs->withAdditionalExtensions( - new CertificatePoliciesExtension(false, new PolicyInformation('1.3.6.1.3.1')) + CertificatePoliciesExtension::create(false, PolicyInformation::create('1.3.6.1.3.1')) ); self::$_cert = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); } @@ -84,8 +84,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_cert); - $config = new PathValidationConfig(new DateTimeImmutable(), 3); + $path = CertificationPath::create(self::$_ca, self::$_cert); + $config = PathValidationConfig::create(new DateTimeImmutable(), 3); $config = $config->withPolicySet('1.3.6.1.3.2'); $result = $path->validate($config); static::assertEmpty($result->policies()); diff --git a/tests/X509/Integration/PathValidation/NotCATest.php b/tests/X509/Integration/PathValidation/NotCATest.php index ae02117f..f3cce486 100644 --- a/tests/X509/Integration/PathValidation/NotCATest.php +++ b/tests/X509/Integration/PathValidation/NotCATest.php @@ -45,16 +45,16 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); - $tbs = $tbs->withAdditionalExtensions(new BasicConstraintsExtension(true, false)); + $tbs = $tbs->withAdditionalExtensions(BasicConstraintsExtension::create(true, false)); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -77,8 +77,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_cert); + $path = CertificationPath::create(self::$_ca, self::$_cert); $this->expectException(PathValidationException::class); - $path->validate(new PathValidationConfig(new DateTimeImmutable(), 3)); + $path->validate(PathValidationConfig::create(new DateTimeImmutable(), 3)); } } diff --git a/tests/X509/Integration/PathValidation/NotKeyCertSignTest.php b/tests/X509/Integration/PathValidation/NotKeyCertSignTest.php index ad467d6e..b27aa634 100644 --- a/tests/X509/Integration/PathValidation/NotKeyCertSignTest.php +++ b/tests/X509/Integration/PathValidation/NotKeyCertSignTest.php @@ -46,19 +46,19 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true), - new KeyUsageExtension(true, KeyUsageExtension::DIGITAL_SIGNATURE) + BasicConstraintsExtension::create(true, true), + KeyUsageExtension::create(true, KeyUsageExtension::DIGITAL_SIGNATURE) ); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -81,8 +81,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_cert); + $path = CertificationPath::create(self::$_ca, self::$_cert); $this->expectException(PathValidationException::class); - $path->validate(new PathValidationConfig(new DateTimeImmutable(), 3)); + $path->validate(PathValidationConfig::create(new DateTimeImmutable(), 3)); } } diff --git a/tests/X509/Integration/PathValidation/PathLengthFailTest.php b/tests/X509/Integration/PathValidation/PathLengthFailTest.php index 89f89574..4b169e28 100644 --- a/tests/X509/Integration/PathValidation/PathLengthFailTest.php +++ b/tests/X509/Integration/PathValidation/PathLengthFailTest.php @@ -54,26 +54,26 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); - $tbs = $tbs->withAdditionalExtensions(new BasicConstraintsExtension(true, true, 0)); + $tbs = $tbs->withAdditionalExtensions(BasicConstraintsExtension::create(true, true, 0)); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create intermediate certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::INTERM_NAME), self::$_intermKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); $tbs = $tbs->withIssuerCertificate(self::$_ca); - $tbs = $tbs->withAdditionalExtensions(new BasicConstraintsExtension(true, true)); + $tbs = $tbs->withAdditionalExtensions(BasicConstraintsExtension::create(true, true)); self::$_interm = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::INTERM_NAME), @@ -98,8 +98,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_interm, self::$_cert); + $path = CertificationPath::create(self::$_ca, self::$_interm, self::$_cert); $this->expectException(PathValidationException::class); - $path->validate(new PathValidationConfig(new DateTimeImmutable(), 3)); + $path->validate(PathValidationConfig::create(new DateTimeImmutable(), 3)); } } diff --git a/tests/X509/Integration/PathValidation/PathLengthTest.php b/tests/X509/Integration/PathValidation/PathLengthTest.php index cfb59540..a25d2e8c 100644 --- a/tests/X509/Integration/PathValidation/PathLengthTest.php +++ b/tests/X509/Integration/PathValidation/PathLengthTest.php @@ -45,16 +45,16 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); - $tbs = $tbs->withAdditionalExtensions(new BasicConstraintsExtension(true, true, 1)); + $tbs = $tbs->withAdditionalExtensions(BasicConstraintsExtension::create(true, true, 1)); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -77,8 +77,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_cert); - $result = $path->validate(new PathValidationConfig(new DateTimeImmutable(), 3)); + $path = CertificationPath::create(self::$_ca, self::$_cert); + $result = $path->validate(PathValidationConfig::create(new DateTimeImmutable(), 3)); static::assertInstanceOf(PathValidationResult::class, $result); } } diff --git a/tests/X509/Integration/PathValidation/PoliciesTest.php b/tests/X509/Integration/PathValidation/PoliciesTest.php index f6002d33..48cbbb4f 100644 --- a/tests/X509/Integration/PathValidation/PoliciesTest.php +++ b/tests/X509/Integration/PathValidation/PoliciesTest.php @@ -47,19 +47,19 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true, 1), - new CertificatePoliciesExtension(false, new PolicyInformation('1.3.6.1.3')) + BasicConstraintsExtension::create(true, true, 1), + CertificatePoliciesExtension::create(false, PolicyInformation::create('1.3.6.1.3')) ); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -67,7 +67,7 @@ public static function setUpBeforeClass(): void ); $tbs = $tbs->withIssuerCertificate(self::$_ca); $tbs = $tbs->withAdditionalExtensions( - new CertificatePoliciesExtension(false, new PolicyInformation('1.3.6.1.3')) + CertificatePoliciesExtension::create(false, PolicyInformation::create('1.3.6.1.3')) ); self::$_cert = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); } @@ -85,8 +85,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_cert); - $config = new PathValidationConfig(new DateTimeImmutable(), 3); + $path = CertificationPath::create(self::$_ca, self::$_cert); + $config = PathValidationConfig::create(new DateTimeImmutable(), 3); $config = $config->withExplicitPolicy(true); $result = $path->validate($config); static::assertInstanceOf(PathValidationResult::class, $result); diff --git a/tests/X509/Integration/PathValidation/PolicyErrorTest.php b/tests/X509/Integration/PathValidation/PolicyErrorTest.php index c85f20d6..da303871 100644 --- a/tests/X509/Integration/PathValidation/PolicyErrorTest.php +++ b/tests/X509/Integration/PathValidation/PolicyErrorTest.php @@ -48,20 +48,20 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true, 1), - new CertificatePoliciesExtension(false, new PolicyInformation('1.3.6.1.3')), - new PolicyConstraintsExtension(true, 0) + BasicConstraintsExtension::create(true, true, 1), + CertificatePoliciesExtension::create(false, PolicyInformation::create('1.3.6.1.3')), + PolicyConstraintsExtension::create(true, 0) ); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -84,8 +84,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_cert); + $path = CertificationPath::create(self::$_ca, self::$_cert); $this->expectException(PathValidationException::class); - $path->validate(new PathValidationConfig(new DateTimeImmutable(), 3)); + $path->validate(PathValidationConfig::create(new DateTimeImmutable(), 3)); } } diff --git a/tests/X509/Integration/PathValidation/PolicyIntersectionAnyPolicyTest.php b/tests/X509/Integration/PathValidation/PolicyIntersectionAnyPolicyTest.php index e3042f4c..0a3693a3 100644 --- a/tests/X509/Integration/PathValidation/PolicyIntersectionAnyPolicyTest.php +++ b/tests/X509/Integration/PathValidation/PolicyIntersectionAnyPolicyTest.php @@ -46,19 +46,19 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true), - new CertificatePoliciesExtension(true, new PolicyInformation(PolicyInformation::OID_ANY_POLICY)) + BasicConstraintsExtension::create(true, true), + CertificatePoliciesExtension::create(true, PolicyInformation::create(PolicyInformation::OID_ANY_POLICY)) ); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -66,7 +66,7 @@ public static function setUpBeforeClass(): void ); $tbs = $tbs->withIssuerCertificate(self::$_ca); $tbs = $tbs->withAdditionalExtensions( - new CertificatePoliciesExtension(true, new PolicyInformation(PolicyInformation::OID_ANY_POLICY)) + CertificatePoliciesExtension::create(true, PolicyInformation::create(PolicyInformation::OID_ANY_POLICY)) ); self::$_cert = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); } @@ -84,8 +84,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_cert); - $config = new PathValidationConfig(new DateTimeImmutable(), 3); + $path = CertificationPath::create(self::$_ca, self::$_cert); + $config = PathValidationConfig::create(new DateTimeImmutable(), 3); $config = $config->withPolicySet('1.3.6.1.3'); $result = $path->validate($config); static::assertEquals('1.3.6.1.3', $result->policies()[0]->oid()); diff --git a/tests/X509/Integration/PathValidation/PolicyIntersectionPruneTest.php b/tests/X509/Integration/PathValidation/PolicyIntersectionPruneTest.php index 94fa5267..dbe5f843 100644 --- a/tests/X509/Integration/PathValidation/PolicyIntersectionPruneTest.php +++ b/tests/X509/Integration/PathValidation/PolicyIntersectionPruneTest.php @@ -47,19 +47,19 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true), - new CertificatePoliciesExtension(true, new PolicyInformation(PolicyInformation::OID_ANY_POLICY)) + BasicConstraintsExtension::create(true, true), + CertificatePoliciesExtension::create(true, PolicyInformation::create(PolicyInformation::OID_ANY_POLICY)) ); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -67,7 +67,7 @@ public static function setUpBeforeClass(): void ); $tbs = $tbs->withIssuerCertificate(self::$_ca); $tbs = $tbs->withAdditionalExtensions( - new CertificatePoliciesExtension(true, new PolicyInformation('1.3.6.1.3.1')) + CertificatePoliciesExtension::create(true, PolicyInformation::create('1.3.6.1.3.1')) ); self::$_cert = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); } @@ -85,8 +85,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_cert); - $config = new PathValidationConfig(new DateTimeImmutable(), 3); + $path = CertificationPath::create(self::$_ca, self::$_cert); + $config = PathValidationConfig::create(new DateTimeImmutable(), 3); $config = $config->withPolicySet('1.3.6.1.3.2') ->withExplicitPolicy(true); $this->expectException(PathValidationException::class); diff --git a/tests/X509/Integration/PathValidation/PolicyIntersectionRemoveTest.php b/tests/X509/Integration/PathValidation/PolicyIntersectionRemoveTest.php index 49373449..2f5b29ff 100644 --- a/tests/X509/Integration/PathValidation/PolicyIntersectionRemoveTest.php +++ b/tests/X509/Integration/PathValidation/PolicyIntersectionRemoveTest.php @@ -55,19 +55,19 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true), - new CertificatePoliciesExtension(true, new PolicyInformation(PolicyInformation::OID_ANY_POLICY)) + BasicConstraintsExtension::create(true, true), + CertificatePoliciesExtension::create(true, PolicyInformation::create(PolicyInformation::OID_ANY_POLICY)) ); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create intermediate certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::INTERM_NAME), self::$_intermKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -75,12 +75,12 @@ public static function setUpBeforeClass(): void ); $tbs = $tbs->withIssuerCertificate(self::$_ca); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true), - new CertificatePoliciesExtension(true, new PolicyInformation(PolicyInformation::OID_ANY_POLICY)) + BasicConstraintsExtension::create(true, true), + CertificatePoliciesExtension::create(true, PolicyInformation::create(PolicyInformation::OID_ANY_POLICY)) ); self::$_interm = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::INTERM_NAME), @@ -88,10 +88,10 @@ public static function setUpBeforeClass(): void ); $tbs = $tbs->withIssuerCertificate(self::$_interm); $tbs = $tbs->withAdditionalExtensions( - new CertificatePoliciesExtension( + CertificatePoliciesExtension::create( true, - new PolicyInformation('1.3.6.1.3.1'), - new PolicyInformation('1.3.6.1.3.2') + PolicyInformation::create('1.3.6.1.3.1'), + PolicyInformation::create('1.3.6.1.3.2') ) ); self::$_cert = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_intermKey); @@ -112,8 +112,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_interm, self::$_cert); - $config = new PathValidationConfig(new DateTimeImmutable(), 3); + $path = CertificationPath::create(self::$_ca, self::$_interm, self::$_cert); + $config = PathValidationConfig::create(new DateTimeImmutable(), 3); $config = $config->withPolicySet('1.3.6.1.3.2'); $result = $path->validate($config); static::assertCount(1, $result->policies()); diff --git a/tests/X509/Integration/PathValidation/PolicyIntersectionSingleExplicitTest.php b/tests/X509/Integration/PathValidation/PolicyIntersectionSingleExplicitTest.php index afd27cfe..e553fbc0 100644 --- a/tests/X509/Integration/PathValidation/PolicyIntersectionSingleExplicitTest.php +++ b/tests/X509/Integration/PathValidation/PolicyIntersectionSingleExplicitTest.php @@ -55,19 +55,19 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true), - new CertificatePoliciesExtension(true, new PolicyInformation('1.3.6.1.3')) + BasicConstraintsExtension::create(true, true), + CertificatePoliciesExtension::create(true, PolicyInformation::create('1.3.6.1.3')) ); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create intermediate certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::INTERM_NAME), self::$_intermKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -75,12 +75,12 @@ public static function setUpBeforeClass(): void ); $tbs = $tbs->withIssuerCertificate(self::$_ca); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true), - new CertificatePoliciesExtension(true, new PolicyInformation('1.3.6.1.3')) + BasicConstraintsExtension::create(true, true), + CertificatePoliciesExtension::create(true, PolicyInformation::create('1.3.6.1.3')) ); self::$_interm = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::INTERM_NAME), @@ -88,7 +88,7 @@ public static function setUpBeforeClass(): void ); $tbs = $tbs->withIssuerCertificate(self::$_interm); $tbs = $tbs->withAdditionalExtensions( - new CertificatePoliciesExtension(true, new PolicyInformation('1.3.6.1.3')) + CertificatePoliciesExtension::create(true, PolicyInformation::create('1.3.6.1.3')) ); self::$_cert = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_intermKey); } @@ -108,8 +108,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_interm, self::$_cert); - $config = new PathValidationConfig(new DateTimeImmutable(), 3); + $path = CertificationPath::create(self::$_ca, self::$_interm, self::$_cert); + $config = PathValidationConfig::create(new DateTimeImmutable(), 3); $config = $config->withPolicySet('1.3.6.1.3'); $result = $path->validate($config); static::assertEquals('1.3.6.1.3', $result->policies()[0]->oid()); diff --git a/tests/X509/Integration/PathValidation/PolicyIntersectionTest.php b/tests/X509/Integration/PathValidation/PolicyIntersectionTest.php index e8db5da6..3aa87617 100644 --- a/tests/X509/Integration/PathValidation/PolicyIntersectionTest.php +++ b/tests/X509/Integration/PathValidation/PolicyIntersectionTest.php @@ -55,19 +55,19 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true), - new CertificatePoliciesExtension(true, new PolicyInformation(PolicyInformation::OID_ANY_POLICY)) + BasicConstraintsExtension::create(true, true), + CertificatePoliciesExtension::create(true, PolicyInformation::create(PolicyInformation::OID_ANY_POLICY)) ); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create intermediate certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::INTERM_NAME), self::$_intermKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -75,12 +75,12 @@ public static function setUpBeforeClass(): void ); $tbs = $tbs->withIssuerCertificate(self::$_ca); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true), - new CertificatePoliciesExtension(true, new PolicyInformation(PolicyInformation::OID_ANY_POLICY)) + BasicConstraintsExtension::create(true, true), + CertificatePoliciesExtension::create(true, PolicyInformation::create(PolicyInformation::OID_ANY_POLICY)) ); self::$_interm = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::INTERM_NAME), @@ -88,9 +88,9 @@ public static function setUpBeforeClass(): void ); $tbs = $tbs->withIssuerCertificate(self::$_interm); $tbs = $tbs->withAdditionalExtensions( - new CertificatePoliciesExtension( + CertificatePoliciesExtension::create( true, - new PolicyInformation('1.3.6.1.3', new UserNoticeQualifier(DisplayText::fromString('Test'))) + PolicyInformation::create('1.3.6.1.3', UserNoticeQualifier::create(DisplayText::fromString('Test'))) ) ); self::$_cert = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_intermKey); @@ -111,8 +111,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_interm, self::$_cert); - $config = new PathValidationConfig(new DateTimeImmutable(), 3); + $path = CertificationPath::create(self::$_ca, self::$_interm, self::$_cert); + $config = PathValidationConfig::create(new DateTimeImmutable(), 3); $config = $config->withPolicySet('1.3.6.1.3'); $result = $path->validate($config); static::assertEquals('Test', $result->policies()[0]->userNoticeQualifier()->explicitText()->string()); diff --git a/tests/X509/Integration/PathValidation/PolicyMappingAnyPolicyTest.php b/tests/X509/Integration/PathValidation/PolicyMappingAnyPolicyTest.php index 8ddd1d27..cfa73364 100644 --- a/tests/X509/Integration/PathValidation/PolicyMappingAnyPolicyTest.php +++ b/tests/X509/Integration/PathValidation/PolicyMappingAnyPolicyTest.php @@ -49,20 +49,23 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true, 1), - new CertificatePoliciesExtension(false, new PolicyInformation('1.3.6.1.3.1')), - new PolicyMappingsExtension(true, new PolicyMapping('1.3.6.1.3.1', PolicyInformation::OID_ANY_POLICY)) + BasicConstraintsExtension::create(true, true, 1), + CertificatePoliciesExtension::create(false, PolicyInformation::create('1.3.6.1.3.1')), + PolicyMappingsExtension::create( + true, + PolicyMapping::create('1.3.6.1.3.1', PolicyInformation::OID_ANY_POLICY) + ) ); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -70,7 +73,7 @@ public static function setUpBeforeClass(): void ); $tbs = $tbs->withIssuerCertificate(self::$_ca); $tbs = $tbs->withAdditionalExtensions( - new CertificatePoliciesExtension(false, new PolicyInformation('1.3.6.1.3.2')) + CertificatePoliciesExtension::create(false, PolicyInformation::create('1.3.6.1.3.2')) ); self::$_cert = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); } @@ -88,8 +91,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_cert); - $config = new PathValidationConfig(new DateTimeImmutable(), 3); + $path = CertificationPath::create(self::$_ca, self::$_cert); + $config = PathValidationConfig::create(new DateTimeImmutable(), 3); $config = $config->withExplicitPolicy(true); $this->expectException(PathValidationException::class); $path->validate($config); diff --git a/tests/X509/Integration/PathValidation/PolicyMappingInhibitTest.php b/tests/X509/Integration/PathValidation/PolicyMappingInhibitTest.php index 742cf856..77b7a5d8 100644 --- a/tests/X509/Integration/PathValidation/PolicyMappingInhibitTest.php +++ b/tests/X509/Integration/PathValidation/PolicyMappingInhibitTest.php @@ -59,20 +59,20 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true), - new CertificatePoliciesExtension(false, new PolicyInformation('1.3.6.1.3.1')), - new PolicyConstraintsExtension(true, 0, 0) + BasicConstraintsExtension::create(true, true), + CertificatePoliciesExtension::create(false, PolicyInformation::create('1.3.6.1.3.1')), + PolicyConstraintsExtension::create(true, 0, 0) ); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create intermediate certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::INTERM_NAME), self::$_intermKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -80,13 +80,13 @@ public static function setUpBeforeClass(): void ); $tbs = $tbs->withIssuerCertificate(self::$_ca); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true), - new CertificatePoliciesExtension(false, new PolicyInformation('1.3.6.1.3.1')), - new PolicyMappingsExtension(true, new PolicyMapping('1.3.6.1.3.1', '1.3.6.1.3.2')) + BasicConstraintsExtension::create(true, true), + CertificatePoliciesExtension::create(false, PolicyInformation::create('1.3.6.1.3.1')), + PolicyMappingsExtension::create(true, PolicyMapping::create('1.3.6.1.3.1', '1.3.6.1.3.2')) ); self::$_interm = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::INTERM_NAME), @@ -94,7 +94,7 @@ public static function setUpBeforeClass(): void ); $tbs = $tbs->withIssuerCertificate(self::$_interm); $tbs = $tbs->withAdditionalExtensions( - new CertificatePoliciesExtension(false, new PolicyInformation('1.3.6.1.3.2')) + CertificatePoliciesExtension::create(false, PolicyInformation::create('1.3.6.1.3.2')) ); self::$_cert = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_intermKey); } @@ -114,8 +114,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_interm, self::$_cert); + $path = CertificationPath::create(self::$_ca, self::$_interm, self::$_cert); $this->expectException(PathValidationException::class); - $path->validate(new PathValidationConfig(new DateTimeImmutable(), 3)); + $path->validate(PathValidationConfig::create(new DateTimeImmutable(), 3)); } } diff --git a/tests/X509/Integration/PathValidation/PolicyMappingMapAnyTest.php b/tests/X509/Integration/PathValidation/PolicyMappingMapAnyTest.php index 267261ec..7dbf10b3 100644 --- a/tests/X509/Integration/PathValidation/PolicyMappingMapAnyTest.php +++ b/tests/X509/Integration/PathValidation/PolicyMappingMapAnyTest.php @@ -50,20 +50,20 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true), - new CertificatePoliciesExtension(true, new PolicyInformation(PolicyInformation::OID_ANY_POLICY)), - new PolicyMappingsExtension(true, new PolicyMapping('1.3.6.1.3.1', '1.3.6.1.3.2')) + BasicConstraintsExtension::create(true, true), + CertificatePoliciesExtension::create(true, PolicyInformation::create(PolicyInformation::OID_ANY_POLICY)), + PolicyMappingsExtension::create(true, PolicyMapping::create('1.3.6.1.3.1', '1.3.6.1.3.2')) ); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -71,7 +71,7 @@ public static function setUpBeforeClass(): void ); $tbs = $tbs->withIssuerCertificate(self::$_ca); $tbs = $tbs->withAdditionalExtensions( - new CertificatePoliciesExtension(true, new PolicyInformation('1.3.6.1.3.2')) + CertificatePoliciesExtension::create(true, PolicyInformation::create('1.3.6.1.3.2')) ); self::$_cert = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); } @@ -89,8 +89,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_cert); - $config = new PathValidationConfig(new DateTimeImmutable(), 3); + $path = CertificationPath::create(self::$_ca, self::$_cert); + $config = PathValidationConfig::create(new DateTimeImmutable(), 3); $config = $config->withExplicitPolicy(true); $result = $path->validate($config); static::assertEquals('1.3.6.1.3.2', $result->policies()[0]->oid()); @@ -101,7 +101,7 @@ public function validate() */ public function coverLogicException() { - $tree = new PolicyTree(PolicyNode::anyPolicyNode()->addChild(PolicyNode::anyPolicyNode())); + $tree = PolicyTree::create(PolicyNode::anyPolicyNode()->addChild(PolicyNode::anyPolicyNode())); $refl = new ReflectionClass($tree); $mtd = $refl->getMethod('_applyAnyPolicyMapping'); $mtd->setAccessible(true); diff --git a/tests/X509/Integration/PathValidation/PolicyMappingTest.php b/tests/X509/Integration/PathValidation/PolicyMappingTest.php index c2ea0695..22fea877 100644 --- a/tests/X509/Integration/PathValidation/PolicyMappingTest.php +++ b/tests/X509/Integration/PathValidation/PolicyMappingTest.php @@ -49,20 +49,20 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true, 1), - new CertificatePoliciesExtension(false, new PolicyInformation('1.3.6.1.3.1')), - new PolicyMappingsExtension(true, new PolicyMapping('1.3.6.1.3.1', '1.3.6.1.3.2')) + BasicConstraintsExtension::create(true, true, 1), + CertificatePoliciesExtension::create(false, PolicyInformation::create('1.3.6.1.3.1')), + PolicyMappingsExtension::create(true, PolicyMapping::create('1.3.6.1.3.1', '1.3.6.1.3.2')) ); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -70,7 +70,7 @@ public static function setUpBeforeClass(): void ); $tbs = $tbs->withIssuerCertificate(self::$_ca); $tbs = $tbs->withAdditionalExtensions( - new CertificatePoliciesExtension(false, new PolicyInformation('1.3.6.1.3.2')) + CertificatePoliciesExtension::create(false, PolicyInformation::create('1.3.6.1.3.2')) ); self::$_cert = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); } @@ -88,8 +88,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_cert); - $config = new PathValidationConfig(new DateTimeImmutable(), 3); + $path = CertificationPath::create(self::$_ca, self::$_cert); + $config = PathValidationConfig::create(new DateTimeImmutable(), 3); $config = $config->withExplicitPolicy(true); $result = $path->validate($config); static::assertInstanceOf(PathValidationResult::class, $result); diff --git a/tests/X509/Integration/PathValidation/PolicyProcessPruneTest.php b/tests/X509/Integration/PathValidation/PolicyProcessPruneTest.php index 2bbb6dbe..7c8b3b70 100644 --- a/tests/X509/Integration/PathValidation/PolicyProcessPruneTest.php +++ b/tests/X509/Integration/PathValidation/PolicyProcessPruneTest.php @@ -48,20 +48,20 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true, 1), - new InhibitAnyPolicyExtension(true, 0), - new CertificatePoliciesExtension(true, new PolicyInformation(PolicyInformation::OID_ANY_POLICY)) + BasicConstraintsExtension::create(true, true, 1), + InhibitAnyPolicyExtension::create(true, 0), + CertificatePoliciesExtension::create(true, PolicyInformation::create(PolicyInformation::OID_ANY_POLICY)) ); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -69,7 +69,7 @@ public static function setUpBeforeClass(): void ); $tbs = $tbs->withIssuerCertificate(self::$_ca); $tbs = $tbs->withAdditionalExtensions( - new CertificatePoliciesExtension(true, new PolicyInformation(PolicyInformation::OID_ANY_POLICY)) + CertificatePoliciesExtension::create(true, PolicyInformation::create(PolicyInformation::OID_ANY_POLICY)) ); self::$_cert = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); } @@ -87,8 +87,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_cert); - $config = new PathValidationConfig(new DateTimeImmutable(), 3); + $path = CertificationPath::create(self::$_ca, self::$_cert); + $config = PathValidationConfig::create(new DateTimeImmutable(), 3); $config = $config->withExplicitPolicy(true); $this->expectException(PathValidationException::class); $path->validate($config); diff --git a/tests/X509/Integration/PathValidation/SignatureMismatchTest.php b/tests/X509/Integration/PathValidation/SignatureMismatchTest.php index 7a69f66e..fc1ce438 100644 --- a/tests/X509/Integration/PathValidation/SignatureMismatchTest.php +++ b/tests/X509/Integration/PathValidation/SignatureMismatchTest.php @@ -44,7 +44,7 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -52,7 +52,7 @@ public static function setUpBeforeClass(): void ); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::CA_NAME), @@ -75,8 +75,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_cert); + $path = CertificationPath::create(self::$_ca, self::$_cert); $this->expectException(PathValidationException::class); - $path->validate(new PathValidationConfig(new DateTimeImmutable(), 3)); + $path->validate(PathValidationConfig::create(new DateTimeImmutable(), 3)); } } diff --git a/tests/X509/Integration/PathValidation/WrapUpPolicyErrorTest.php b/tests/X509/Integration/PathValidation/WrapUpPolicyErrorTest.php index 3376438f..28b0b790 100644 --- a/tests/X509/Integration/PathValidation/WrapUpPolicyErrorTest.php +++ b/tests/X509/Integration/PathValidation/WrapUpPolicyErrorTest.php @@ -48,26 +48,26 @@ public static function setUpBeforeClass(): void PEM::fromFile(TEST_ASSETS_DIR . '/certs/keys/acme-rsa.pem') )->privateKeyInfo(); // create CA certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CA_NAME), self::$_caKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); $tbs = $tbs->withAdditionalExtensions( - new BasicConstraintsExtension(true, true, 1), - new CertificatePoliciesExtension(false, new PolicyInformation('1.3.6.1.3')) + BasicConstraintsExtension::create(true, true, 1), + CertificatePoliciesExtension::create(false, PolicyInformation::create('1.3.6.1.3')) ); self::$_ca = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); // create end-entity certificate - $tbs = new TBSCertificate( + $tbs = TBSCertificate::create( Name::fromString(self::CERT_NAME), self::$_certKey->publicKeyInfo(), Name::fromString(self::CA_NAME), Validity::fromStrings(null, 'now + 1 hour') ); $tbs = $tbs->withIssuerCertificate(self::$_ca); - $tbs = $tbs->withAdditionalExtensions(new PolicyConstraintsExtension(true, 0)); + $tbs = $tbs->withAdditionalExtensions(PolicyConstraintsExtension::create(true, 0)); self::$_cert = $tbs->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_caKey); } @@ -84,8 +84,8 @@ public static function tearDownAfterClass(): void */ public function validate() { - $path = new CertificationPath(self::$_ca, self::$_cert); + $path = CertificationPath::create(self::$_ca, self::$_cert); $this->expectException(PathValidationException::class); - $path->validate(new PathValidationConfig(new DateTimeImmutable(), 3)); + $path->validate(PathValidationConfig::create(new DateTimeImmutable(), 3)); } } diff --git a/tests/X509/Integration/Workflow/RequestToCertTest.php b/tests/X509/Integration/Workflow/RequestToCertTest.php index e407b1eb..79246aa0 100644 --- a/tests/X509/Integration/Workflow/RequestToCertTest.php +++ b/tests/X509/Integration/Workflow/RequestToCertTest.php @@ -54,12 +54,12 @@ public function createCA() $name = Name::fromString('cn=Issuer'); $validity = Validity::fromStrings('2016-05-02 12:00:00', '2016-05-03 12:00:00'); $pki = self::$_issuerKey->publicKeyInfo(); - $tbs_cert = new TBSCertificate($name, $pki, $name, $validity); + $tbs_cert = TBSCertificate::create($name, $pki, $name, $validity); $tbs_cert = $tbs_cert->withExtensions( - new Extensions( - new BasicConstraintsExtension(true, true), - new SubjectKeyIdentifierExtension(false, $pki->keyIdentifier()), - new KeyUsageExtension(true, KeyUsageExtension::DIGITAL_SIGNATURE | KeyUsageExtension::KEY_CERT_SIGN) + Extensions::create( + BasicConstraintsExtension::create(true, true), + SubjectKeyIdentifierExtension::create(false, $pki->keyIdentifier()), + KeyUsageExtension::create(true, KeyUsageExtension::DIGITAL_SIGNATURE | KeyUsageExtension::KEY_CERT_SIGN) ) ); $algo = SHA256WithRSAEncryptionAlgorithmIdentifier::create(); @@ -75,8 +75,8 @@ public function createRequest() { $subject = Name::fromString('cn=Subject'); $pkinfo = self::$_subjectKey->publicKeyInfo(); - $cri = new CertificationRequestInfo($subject, $pkinfo); - $cri = $cri->withExtensionRequest(new Extensions(new BasicConstraintsExtension(true, false))); + $cri = CertificationRequestInfo::create($subject, $pkinfo); + $cri = $cri->withExtensionRequest(Extensions::create(BasicConstraintsExtension::create(true, false))); $algo = ECDSAWithSHA1AlgorithmIdentifier::create(); $csr = $cri->sign($algo, self::$_subjectKey); static::assertInstanceOf(CertificationRequest::class, $csr); @@ -95,8 +95,8 @@ public function issueCertificate(CertificationRequest $csr, Certificate $ca_cert $validity = Validity::fromStrings('2016-05-02 12:00:00', '2016-05-02 13:00:00'); $tbs_cert = $tbs_cert->withValidity($validity); $tbs_cert = $tbs_cert->withAdditionalExtensions( - new KeyUsageExtension(true, KeyUsageExtension::DIGITAL_SIGNATURE | KeyUsageExtension::KEY_ENCIPHERMENT), - new BasicConstraintsExtension(true, false) + KeyUsageExtension::create(true, KeyUsageExtension::DIGITAL_SIGNATURE | KeyUsageExtension::KEY_ENCIPHERMENT), + BasicConstraintsExtension::create(true, false) ); $algo = SHA512WithRSAEncryptionAlgorithmIdentifier::create(); $cert = $tbs_cert->sign($algo, self::$_issuerKey); diff --git a/tests/X509/Unit/Ac/AttCertValidityPeriodTest.php b/tests/X509/Unit/Ac/AttCertValidityPeriodTest.php index 50334433..c14c7f5d 100644 --- a/tests/X509/Unit/Ac/AttCertValidityPeriodTest.php +++ b/tests/X509/Unit/Ac/AttCertValidityPeriodTest.php @@ -32,9 +32,9 @@ public static function tearDownAfterClass(): void /** * @test */ - public function create() + public function create(): AttCertValidityPeriod { - $validity = new AttCertValidityPeriod(self::$_nb, self::$_na); + $validity = AttCertValidityPeriod::create(self::$_nb, self::$_na); static::assertInstanceOf(AttCertValidityPeriod::class, $validity); return $validity; } @@ -44,7 +44,7 @@ public function create() * * @test */ - public function encode(AttCertValidityPeriod $validity) + public function encode(AttCertValidityPeriod $validity): string { $seq = $validity->toASN1(); static::assertInstanceOf(Sequence::class, $seq); @@ -58,7 +58,7 @@ public function encode(AttCertValidityPeriod $validity) * * @test */ - public function decode($data) + public function decode($data): AttCertValidityPeriod { $iss_ser = AttCertValidityPeriod::fromASN1(Sequence::fromDER($data)); static::assertInstanceOf(AttCertValidityPeriod::class, $iss_ser); diff --git a/tests/X509/Unit/Ac/Attribute/IetfAttrValueTest.php b/tests/X509/Unit/Ac/Attribute/IetfAttrValueTest.php index e3247562..6a1a0921 100644 --- a/tests/X509/Unit/Ac/Attribute/IetfAttrValueTest.php +++ b/tests/X509/Unit/Ac/Attribute/IetfAttrValueTest.php @@ -31,7 +31,7 @@ public function fromUnsupportedTypeFail() */ public function toUnsupportedTypeFail() { - $val = new IetfAttrValue('', Element::TYPE_NULL); + $val = IetfAttrValue::create('', Element::TYPE_NULL); $this->expectException(LogicException::class); $val->toASN1(); } diff --git a/tests/X509/Unit/Ac/Attribute/RoleTest.php b/tests/X509/Unit/Ac/Attribute/RoleTest.php index a7986bce..67428739 100644 --- a/tests/X509/Unit/Ac/Attribute/RoleTest.php +++ b/tests/X509/Unit/Ac/Attribute/RoleTest.php @@ -31,7 +31,7 @@ final class RoleTest extends TestCase */ public function create() { - $value = new RoleAttributeValue( + $value = RoleAttributeValue::create( UniformResourceIdentifier::create(self::ROLE_URI), GeneralNames::create(DirectoryName::fromDNString(self::AUTHORITY_DN)) ); @@ -167,7 +167,7 @@ public function allFromMultipleAttributes() */ public function createWithoutAuthority() { - $value = new RoleAttributeValue(UniformResourceIdentifier::create(self::ROLE_URI)); + $value = RoleAttributeValue::create(UniformResourceIdentifier::create(self::ROLE_URI)); static::assertInstanceOf(RoleAttributeValue::class, $value); return $value; } diff --git a/tests/X509/Unit/Ac/Attribute/SvceAuthInfoTest.php b/tests/X509/Unit/Ac/Attribute/SvceAuthInfoTest.php index 8c6794a8..414c0586 100644 --- a/tests/X509/Unit/Ac/Attribute/SvceAuthInfoTest.php +++ b/tests/X509/Unit/Ac/Attribute/SvceAuthInfoTest.php @@ -22,7 +22,7 @@ final class SvceAuthInfoTest extends TestCase */ public function createWithoutAuthInfo() { - $val = new AccessIdentityAttributeValue( + $val = AccessIdentityAttributeValue::create( DirectoryName::fromDNString('cn=Svc'), DirectoryName::fromDNString('cn=Ident') ); diff --git a/tests/X509/Unit/Ac/AttributeCertificateInfoTest.php b/tests/X509/Unit/Ac/AttributeCertificateInfoTest.php index cd2fe152..222ce7ee 100644 --- a/tests/X509/Unit/Ac/AttributeCertificateInfoTest.php +++ b/tests/X509/Unit/Ac/AttributeCertificateInfoTest.php @@ -53,15 +53,15 @@ final class AttributeCertificateInfoTest extends TestCase public static function setUpBeforeClass(): void { - self::$_holder = new Holder( - new IssuerSerial(GeneralNames::create(DirectoryName::fromDNString(self::ISSUER_DN)), 42) + self::$_holder = Holder::create( + IssuerSerial::create(GeneralNames::create(DirectoryName::fromDNString(self::ISSUER_DN)), '42') ); self::$_issuer = AttCertIssuer::fromName(Name::fromString(self::ISSUER_DN)); self::$_validity = AttCertValidityPeriod::fromStrings('2016-04-29 12:00:00', '2016-04-29 13:00:00'); self::$_attribs = Attributes::fromAttributeValues( - new RoleAttributeValue(UniformResourceIdentifier::create('urn:admin')) + RoleAttributeValue::create(UniformResourceIdentifier::create('urn:admin')) ); - self::$_extensions = new Extensions(new AuthorityKeyIdentifierExtension(true, 'test')); + self::$_extensions = Extensions::create(AuthorityKeyIdentifierExtension::create(true, 'test')); self::$_privKeyInfo = PrivateKeyInfo::fromPEM(PEM::fromFile(TEST_ASSETS_DIR . '/rsa/private_key.pem')); } @@ -80,7 +80,7 @@ public static function tearDownAfterClass(): void */ public function create() { - $aci = new AttributeCertificateInfo(self::$_holder, self::$_issuer, self::$_validity, self::$_attribs); + $aci = AttributeCertificateInfo::create(self::$_holder, self::$_issuer, self::$_validity, self::$_attribs); static::assertInstanceOf(AttributeCertificateInfo::class, $aci); return $aci; } @@ -90,7 +90,7 @@ public function create() */ public function createWithAll() { - $aci = new AttributeCertificateInfo(self::$_holder, self::$_issuer, self::$_validity, self::$_attribs); + $aci = AttributeCertificateInfo::create(self::$_holder, self::$_issuer, self::$_validity, self::$_attribs); $aci = $aci->withSignature(SHA256WithRSAEncryptionAlgorithmIdentifier::create()) ->withSerialNumber(1) ->withExtensions(self::$_extensions) @@ -335,7 +335,7 @@ public function withExtensions(AttributeCertificateInfo $aci) */ public function withAdditionalExtensions(AttributeCertificateInfo $aci) { - $aci = $aci->withAdditionalExtensions(new AuthorityKeyIdentifierExtension(true, 'test')); + $aci = $aci->withAdditionalExtensions(AuthorityKeyIdentifierExtension::create(true, 'test')); static::assertInstanceOf(AttributeCertificateInfo::class, $aci); return $aci; } diff --git a/tests/X509/Unit/Ac/AttributeCertificateTest.php b/tests/X509/Unit/Ac/AttributeCertificateTest.php index 7080b841..a5fb8917 100644 --- a/tests/X509/Unit/Ac/AttributeCertificateTest.php +++ b/tests/X509/Unit/Ac/AttributeCertificateTest.php @@ -56,18 +56,20 @@ public static function tearDownAfterClass(): void */ public function create(): AttributeCertificate { - $holder = new Holder(new IssuerSerial(GeneralNames::create(DirectoryName::fromDNString('cn=Issuer')), 42)); + $holder = Holder::create( + IssuerSerial::create(GeneralNames::create(DirectoryName::fromDNString('cn=Issuer')), '42') + ); $issuer = AttCertIssuer::fromName(Name::fromString('cn=Issuer')); $validity = AttCertValidityPeriod::fromStrings('2016-04-29 12:00:00', '2016-04-29 13:00:00'); $attribs = Attributes::fromAttributeValues( - new RoleAttributeValue(UniformResourceIdentifier::create('urn:admin')) + RoleAttributeValue::create(UniformResourceIdentifier::create('urn:admin')) ); - $acinfo = new AttributeCertificateInfo($holder, $issuer, $validity, $attribs); + $acinfo = AttributeCertificateInfo::create($holder, $issuer, $validity, $attribs); $algo = SHA256WithRSAEncryptionAlgorithmIdentifier::create(); $acinfo = $acinfo->withSignature($algo) ->withSerialNumber(1); $signature = Crypto::getDefault()->sign($acinfo->toASN1()->toDER(), self::$_privateKeyInfo, $algo); - $ac = new AttributeCertificate($acinfo, $algo, $signature); + $ac = AttributeCertificate::create($acinfo, $algo, $signature); static::assertInstanceOf(AttributeCertificate::class, $ac); return $ac; } diff --git a/tests/X509/Unit/Ac/AttributesTest.php b/tests/X509/Unit/Ac/AttributesTest.php index 1fc86835..041e9d2d 100644 --- a/tests/X509/Unit/Ac/AttributesTest.php +++ b/tests/X509/Unit/Ac/AttributesTest.php @@ -27,11 +27,11 @@ final class AttributesTest extends TestCase public function create(): Attributes { $attribs = Attributes::fromAttributeValues( - new AccessIdentityAttributeValue( + AccessIdentityAttributeValue::create( UniformResourceIdentifier::create('urn:service'), UniformResourceIdentifier::create('urn:ident') ), - new RoleAttributeValue(UniformResourceIdentifier::create('urn:admin')), + RoleAttributeValue::create(UniformResourceIdentifier::create('urn:admin')), DescriptionValue::create('test') ); static::assertInstanceOf(Attributes::class, $attribs); @@ -151,7 +151,7 @@ public function withAdditional(Attributes $attribs): void public function withUniqueReplace(Attributes $attribs): void { $attribs = $attribs->withUnique( - Attribute::fromAttributeValues(new RoleAttributeValue(UniformResourceIdentifier::create('uri:new'))) + Attribute::fromAttributeValues(RoleAttributeValue::create(UniformResourceIdentifier::create('uri:new'))) ); static::assertInstanceOf(Attributes::class, $attribs); static::assertCount(3, $attribs); diff --git a/tests/X509/Unit/Ac/HolderTest.php b/tests/X509/Unit/Ac/HolderTest.php index 5ff534e5..e6af783f 100644 --- a/tests/X509/Unit/Ac/HolderTest.php +++ b/tests/X509/Unit/Ac/HolderTest.php @@ -28,9 +28,9 @@ final class HolderTest extends TestCase public static function setUpBeforeClass(): void { - self::$_issuerSerial = new IssuerSerial(GeneralNames::create(DirectoryName::fromDNString('cn=Test')), 1); + self::$_issuerSerial = IssuerSerial::create(GeneralNames::create(DirectoryName::fromDNString('cn=Test')), '1'); self::$_subject = GeneralNames::create(DirectoryName::fromDNString('cn=Subject')); - self::$_odi = new ObjectDigestInfo( + self::$_odi = ObjectDigestInfo::create( ObjectDigestInfo::TYPE_PUBLIC_KEY, SHA1WithRSAEncryptionAlgorithmIdentifier::create(), BitString::create('') @@ -49,7 +49,7 @@ public static function tearDownAfterClass(): void */ public function create() { - $holder = new Holder(self::$_issuerSerial, self::$_subject); + $holder = Holder::create(self::$_issuerSerial, self::$_subject); $holder = $holder->withObjectDigestInfo(self::$_odi); static::assertInstanceOf(Holder::class, $holder); return $holder; @@ -127,7 +127,7 @@ public function objectDigestInfo(Holder $holder) */ public function withBaseCertificateID() { - $holder = new Holder(); + $holder = Holder::create(); $holder = $holder->withBaseCertificateID(self::$_issuerSerial); static::assertInstanceOf(Holder::class, $holder); } @@ -137,7 +137,7 @@ public function withBaseCertificateID() */ public function withEntityName() { - $holder = new Holder(); + $holder = Holder::create(); $holder = $holder->withEntityName(self::$_subject); static::assertInstanceOf(Holder::class, $holder); } @@ -147,7 +147,7 @@ public function withEntityName() */ public function withObjectDigestInfo() { - $holder = new Holder(); + $holder = Holder::create(); $holder = $holder->withObjectDigestInfo(self::$_odi); static::assertInstanceOf(Holder::class, $holder); } @@ -157,7 +157,7 @@ public function withObjectDigestInfo() */ public function noBaseCertificateIDFail() { - $holder = new Holder(); + $holder = Holder::create(); $this->expectException(LogicException::class); $holder->baseCertificateID(); } @@ -167,7 +167,7 @@ public function noBaseCertificateIDFail() */ public function noEntityNameFail() { - $holder = new Holder(); + $holder = Holder::create(); $this->expectException(LogicException::class); $holder->entityName(); } @@ -177,7 +177,7 @@ public function noEntityNameFail() */ public function noObjectDigestInfoFail() { - $holder = new Holder(); + $holder = Holder::create(); $this->expectException(LogicException::class); $holder->objectDigestInfo(); } diff --git a/tests/X509/Unit/Ac/IssuerSerialTest.php b/tests/X509/Unit/Ac/IssuerSerialTest.php index 4b9a34f9..839321b5 100644 --- a/tests/X509/Unit/Ac/IssuerSerialTest.php +++ b/tests/X509/Unit/Ac/IssuerSerialTest.php @@ -25,7 +25,7 @@ final class IssuerSerialTest extends TestCase public static function setUpBeforeClass(): void { self::$_issuer = GeneralNames::create(DirectoryName::fromDNString('cn=Test')); - self::$_uid = new UniqueIdentifier(BitString::create(hex2bin('ff'))); + self::$_uid = UniqueIdentifier::create(BitString::create(hex2bin('ff'))); } public static function tearDownAfterClass(): void @@ -39,7 +39,7 @@ public static function tearDownAfterClass(): void */ public function create() { - $iss_ser = new IssuerSerial(self::$_issuer, 1, self::$_uid); + $iss_ser = IssuerSerial::create(self::$_issuer, '1', self::$_uid); static::assertInstanceOf(IssuerSerial::class, $iss_ser); return $iss_ser; } @@ -116,7 +116,7 @@ public function issuerUID(IssuerSerial $is) */ public function noIssuerUIDFail() { - $is = new IssuerSerial(self::$_issuer, 1); + $is = IssuerSerial::create(self::$_issuer, '1'); $this->expectException(LogicException::class); $is->issuerUID(); } diff --git a/tests/X509/Unit/Ac/ObjectDigestInfoTest.php b/tests/X509/Unit/Ac/ObjectDigestInfoTest.php index a57193f2..e1ba40d0 100644 --- a/tests/X509/Unit/Ac/ObjectDigestInfoTest.php +++ b/tests/X509/Unit/Ac/ObjectDigestInfoTest.php @@ -20,9 +20,9 @@ final class ObjectDigestInfoTest extends TestCase /** * @test */ - public function create() + public function create(): ObjectDigestInfo { - $odi = new ObjectDigestInfo( + $odi = ObjectDigestInfo::create( ObjectDigestInfo::TYPE_PUBLIC_KEY, SHA1WithRSAEncryptionAlgorithmIdentifier::create(), BitString::create(hex2bin('ff')) @@ -36,7 +36,7 @@ public function create() * * @test */ - public function encode(ObjectDigestInfo $odi) + public function encode(ObjectDigestInfo $odi): string { $seq = $odi->toASN1(); static::assertInstanceOf(Sequence::class, $seq); @@ -50,7 +50,7 @@ public function encode(ObjectDigestInfo $odi) * * @test */ - public function decode($data) + public function decode($data): ObjectDigestInfo { $odi = ObjectDigestInfo::fromASN1(Sequence::fromDER($data)); static::assertInstanceOf(ObjectDigestInfo::class, $odi); @@ -63,7 +63,7 @@ public function decode($data) * * @test */ - public function recoded(ObjectDigestInfo $ref, ObjectDigestInfo $new) + public function recoded(ObjectDigestInfo $ref, ObjectDigestInfo $new): void { static::assertEquals($ref, $new); } @@ -71,7 +71,7 @@ public function recoded(ObjectDigestInfo $ref, ObjectDigestInfo $new) /** * @test */ - public function decodeWithOtherObjectTypeID() + public function decodeWithOtherObjectTypeID(): ObjectDigestInfo { $algo = SHA1WithRSAEncryptionAlgorithmIdentifier::create(); $seq = Sequence::create( @@ -90,7 +90,7 @@ public function decodeWithOtherObjectTypeID() * * @test */ - public function encodeWithOtherObjectTypeID(ObjectDigestInfo $odi) + public function encodeWithOtherObjectTypeID(ObjectDigestInfo $odi): void { $seq = $odi->toASN1(); static::assertInstanceOf(Sequence::class, $seq); diff --git a/tests/X509/Unit/Ac/V2FormTest.php b/tests/X509/Unit/Ac/V2FormTest.php index a85944d0..6d59bdac 100644 --- a/tests/X509/Unit/Ac/V2FormTest.php +++ b/tests/X509/Unit/Ac/V2FormTest.php @@ -40,7 +40,7 @@ public static function tearDownAfterClass(): void */ public function create() { - $issuer = new V2Form(self::$_issuerName); + $issuer = V2Form::create(self::$_issuerName); static::assertInstanceOf(AttCertIssuer::class, $issuer); return $issuer; } @@ -97,7 +97,7 @@ public function issuerName(V2Form $issuer) */ public function noIssuerNameFail() { - $issuer = new V2Form(); + $issuer = V2Form::create(); $this->expectException(LogicException::class); $issuer->issuerName(); } @@ -117,8 +117,8 @@ public function name(V2Form $issuer) */ public function decodeWithAll() { - $iss_ser = new IssuerSerial(self::$_issuerName, 1); - $odi = new ObjectDigestInfo( + $iss_ser = IssuerSerial::create(self::$_issuerName, '1'); + $odi = ObjectDigestInfo::create( ObjectDigestInfo::TYPE_PUBLIC_KEY, SHA1WithRSAEncryptionAlgorithmIdentifier::create(), BitString::create('') diff --git a/tests/X509/Unit/Certificate/CertificateBundleTest.php b/tests/X509/Unit/Certificate/CertificateBundleTest.php index e6dd9df1..695b3567 100644 --- a/tests/X509/Unit/Certificate/CertificateBundleTest.php +++ b/tests/X509/Unit/Certificate/CertificateBundleTest.php @@ -57,7 +57,7 @@ public static function tearDownAfterClass(): void */ public function create() { - $bundle = new CertificateBundle(self::$_cert1, self::$_cert2); + $bundle = CertificateBundle::create(self::$_cert1, self::$_cert2); static::assertInstanceOf(CertificateBundle::class, $bundle); return $bundle; } @@ -112,7 +112,7 @@ public function contains(CertificateBundle $bundle) */ public function doesNotContain() { - $bundle = new CertificateBundle(self::$_cert1, self::$_cert2); + $bundle = CertificateBundle::create(self::$_cert1, self::$_cert2); static::assertFalse($bundle->contains(self::$_cert3)); } @@ -122,7 +122,7 @@ public function doesNotContain() public function containsSubjectMismatch() { $priv_key_info = PrivateKeyInfo::fromPEM(PEM::fromFile(TEST_ASSETS_DIR . '/rsa/private_key.pem')); - $tc = new TBSCertificate( + $tc = TBSCertificate::create( Name::fromString('cn=Subject'), $priv_key_info->publicKeyInfo(), Name::fromString('cn=Issuer 1'), @@ -131,7 +131,7 @@ public function containsSubjectMismatch() $cert1 = $tc->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), $priv_key_info); $tc = $tc->withSubject(Name::fromString('cn=Issuer 2')); $cert2 = $tc->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), $priv_key_info); - $bundle = new CertificateBundle($cert1); + $bundle = CertificateBundle::create($cert1); static::assertFalse($bundle->contains($cert2)); } @@ -207,14 +207,14 @@ public function fromPEMs() public function searchBySubjectKeyHavingNoID() { $priv_key_info = PrivateKeyInfo::fromPEM(PEM::fromFile(TEST_ASSETS_DIR . '/rsa/private_key.pem')); - $tc = new TBSCertificate( + $tc = TBSCertificate::create( Name::fromString('cn=Subject'), $priv_key_info->publicKeyInfo(), Name::fromString('cn=Issuer'), Validity::fromStrings(null, null) ); $cert = $tc->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), $priv_key_info); - $bundle = new CertificateBundle($cert); + $bundle = CertificateBundle::create($cert); static::assertEmpty($bundle->allBySubjectKeyIdentifier('nope')); } } diff --git a/tests/X509/Unit/Certificate/CertificateChainTest.php b/tests/X509/Unit/Certificate/CertificateChainTest.php index f4b6012b..d3bb1c02 100644 --- a/tests/X509/Unit/Certificate/CertificateChainTest.php +++ b/tests/X509/Unit/Certificate/CertificateChainTest.php @@ -40,7 +40,7 @@ public static function tearDownAfterClass(): void */ public function createChain() { - $chain = new CertificateChain(...self::$_certs); + $chain = CertificateChain::create(...self::$_certs); static::assertInstanceOf(CertificateChain::class, $chain); return $chain; } @@ -71,7 +71,7 @@ public function endEntityCert(CertificateChain $chain) */ public function endEntityCertFail() { - $chain = new CertificateChain(); + $chain = CertificateChain::create(); $this->expectException(LogicException::class); $chain->endEntityCertificate(); } @@ -91,7 +91,7 @@ public function trustAnchorCert(CertificateChain $chain) */ public function trustAnchorCertFail() { - $chain = new CertificateChain(); + $chain = CertificateChain::create(); $this->expectException(LogicException::class); $chain->trustAnchorCertificate(); } diff --git a/tests/X509/Unit/Certificate/CertificateTest.php b/tests/X509/Unit/Certificate/CertificateTest.php index 9a3f1151..b6c36098 100644 --- a/tests/X509/Unit/Certificate/CertificateTest.php +++ b/tests/X509/Unit/Certificate/CertificateTest.php @@ -43,7 +43,7 @@ public static function tearDownAfterClass(): void public function create() { $pki = self::$_privateKeyInfo->publicKeyInfo(); - $tc = new TBSCertificate( + $tc = TBSCertificate::create( Name::fromString('cn=Subject'), $pki, Name::fromString('cn=Issuer'), @@ -53,7 +53,7 @@ public function create() ->withSerialNumber(0) ->withSignature(SHA1WithRSAEncryptionAlgorithmIdentifier::create()); $signature = Crypto::getDefault()->sign($tc->toASN1()->toDER(), self::$_privateKeyInfo, $tc->signature()); - $cert = new Certificate($tc, $tc->signature(), $signature); + $cert = Certificate::create($tc, $tc->signature(), $signature); static::assertInstanceOf(Certificate::class, $cert); return $cert; } diff --git a/tests/X509/Unit/Certificate/CertificateVersionTest.php b/tests/X509/Unit/Certificate/CertificateVersionTest.php index 53737205..3262b7f6 100644 --- a/tests/X509/Unit/Certificate/CertificateVersionTest.php +++ b/tests/X509/Unit/Certificate/CertificateVersionTest.php @@ -31,7 +31,7 @@ public static function setUpBeforeClass(): void $issuer = Name::fromString('cn=Test Issuer'); $pki = self::$_privateKeyInfo->publicKeyInfo(); $validity = Validity::fromStrings('now', 'now + 1 day', 'UTC'); - self::$_tbsCert = new TBSCertificate($subject, $pki, $issuer, $validity); + self::$_tbsCert = TBSCertificate::create($subject, $pki, $issuer, $validity); } public static function tearDownAfterClass(): void @@ -87,7 +87,7 @@ public function version2BothUID() public function version3() { $tbsCert = self::$_tbsCert->withExtensions( - new Extensions(new KeyUsageExtension(true, KeyUsageExtension::DIGITAL_SIGNATURE)) + Extensions::create(KeyUsageExtension::create(true, KeyUsageExtension::DIGITAL_SIGNATURE)) ); $cert = $tbsCert->sign(SHA1WithRSAEncryptionAlgorithmIdentifier::create(), self::$_privateKeyInfo); static::assertEquals($cert->tbsCertificate()->version(), TBSCertificate::VERSION_3); diff --git a/tests/X509/Unit/Certificate/Extension/AAControlsTest.php b/tests/X509/Unit/Certificate/Extension/AAControlsTest.php index 03f6e173..8f7db6f5 100644 --- a/tests/X509/Unit/Certificate/Extension/AAControlsTest.php +++ b/tests/X509/Unit/Certificate/Extension/AAControlsTest.php @@ -20,7 +20,7 @@ final class AAControlsTest extends TestCase */ public function create() { - $ext = new AAControlsExtension(true, 3, ['1.2.3.4'], ['1.2.3.5', '1.2.3.6'], false); + $ext = AAControlsExtension::create(true, 3, ['1.2.3.4'], ['1.2.3.5', '1.2.3.6'], false); static::assertInstanceOf(AAControlsExtension::class, $ext); return $ext; } @@ -127,7 +127,7 @@ public function unspecified(AAControlsExtension $ext) */ public function createEmpty() { - $ext = new AAControlsExtension(false); + $ext = AAControlsExtension::create(false); static::assertInstanceOf(AAControlsExtension::class, $ext); return $ext; } diff --git a/tests/X509/Unit/Certificate/Extension/AccessDescription/AuthorityAccessDescriptionTest.php b/tests/X509/Unit/Certificate/Extension/AccessDescription/AuthorityAccessDescriptionTest.php index f0f6d154..44ad9449 100644 --- a/tests/X509/Unit/Certificate/Extension/AccessDescription/AuthorityAccessDescriptionTest.php +++ b/tests/X509/Unit/Certificate/Extension/AccessDescription/AuthorityAccessDescriptionTest.php @@ -21,7 +21,7 @@ final class AuthorityAccessDescriptionTest extends TestCase */ public function create() { - $desc = new AuthorityAccessDescription( + $desc = AuthorityAccessDescription::create( AuthorityAccessDescription::OID_METHOD_OSCP, UniformResourceIdentifier::create(self::URI) ); diff --git a/tests/X509/Unit/Certificate/Extension/AccessDescription/SubjectAccessDescriptionTest.php b/tests/X509/Unit/Certificate/Extension/AccessDescription/SubjectAccessDescriptionTest.php index 052650c8..e39773b8 100644 --- a/tests/X509/Unit/Certificate/Extension/AccessDescription/SubjectAccessDescriptionTest.php +++ b/tests/X509/Unit/Certificate/Extension/AccessDescription/SubjectAccessDescriptionTest.php @@ -19,9 +19,9 @@ final class SubjectAccessDescriptionTest extends TestCase /** * @test */ - public function create() + public function create(): SubjectAccessDescription { - $desc = new SubjectAccessDescription( + $desc = SubjectAccessDescription::create( SubjectAccessDescription::OID_METHOD_CA_REPOSITORY, UniformResourceIdentifier::create(self::URI) ); diff --git a/tests/X509/Unit/Certificate/Extension/AuthorityInformationAccessTest.php b/tests/X509/Unit/Certificate/Extension/AuthorityInformationAccessTest.php index 1050240b..a2615471 100644 --- a/tests/X509/Unit/Certificate/Extension/AuthorityInformationAccessTest.php +++ b/tests/X509/Unit/Certificate/Extension/AuthorityInformationAccessTest.php @@ -21,13 +21,13 @@ final class AuthorityInformationAccessTest extends TestCase */ public function create() { - $ext = new AuthorityInformationAccessExtension( + $ext = AuthorityInformationAccessExtension::create( false, - new AuthorityAccessDescription( + AuthorityAccessDescription::create( AuthorityAccessDescription::OID_METHOD_CA_ISSUERS, UniformResourceIdentifier::create('urn:test') ), - new AuthorityAccessDescription( + AuthorityAccessDescription::create( AuthorityAccessDescription::OID_METHOD_OSCP, UniformResourceIdentifier::create('https://oscp.example.com/') ) diff --git a/tests/X509/Unit/Certificate/Extension/AuthorityKeyIdentifierTest.php b/tests/X509/Unit/Certificate/Extension/AuthorityKeyIdentifierTest.php index 4609955a..56ab22dc 100644 --- a/tests/X509/Unit/Certificate/Extension/AuthorityKeyIdentifierTest.php +++ b/tests/X509/Unit/Certificate/Extension/AuthorityKeyIdentifierTest.php @@ -28,9 +28,9 @@ final class AuthorityKeyIdentifierTest extends TestCase { final public const KEY_ID = 'test-id'; - final public const SERIAL = 42; + final public const SERIAL = '42'; - private static $_issuer; + private static ?GeneralNames $_issuer; public static function setUpBeforeClass(): void { @@ -45,9 +45,9 @@ public static function tearDownAfterClass(): void /** * @test */ - public function create() + public function create(): AuthorityKeyIdentifierExtension { - $ext = new AuthorityKeyIdentifierExtension(true, self::KEY_ID, self::$_issuer, self::SERIAL); + $ext = AuthorityKeyIdentifierExtension::create(true, self::KEY_ID, self::$_issuer, self::SERIAL); static::assertInstanceOf(AuthorityKeyIdentifierExtension::class, $ext); return $ext; } @@ -55,7 +55,7 @@ public function create() /** * @test */ - public function fromPKI() + public function fromPKI(): void { $pki = PublicKeyInfo::fromPEM(PEM::fromFile(TEST_ASSETS_DIR . '/rsa/public_key.pem')); $ext = AuthorityKeyIdentifierExtension::fromPublicKeyInfo($pki); @@ -67,7 +67,7 @@ public function fromPKI() * * @test */ - public function oID(Extension $ext) + public function oID(Extension $ext): void { static::assertEquals(Extension::OID_AUTHORITY_KEY_IDENTIFIER, $ext->oid()); } @@ -77,7 +77,7 @@ public function oID(Extension $ext) * * @test */ - public function critical(Extension $ext) + public function critical(Extension $ext): void { static::assertTrue($ext->isCritical()); } @@ -87,7 +87,7 @@ public function critical(Extension $ext) * * @test */ - public function encode(Extension $ext) + public function encode(Extension $ext): string { $seq = $ext->toASN1(); static::assertInstanceOf(Sequence::class, $seq); @@ -114,7 +114,7 @@ public function decode($der) * * @test */ - public function recoded(Extension $ref, Extension $new) + public function recoded(Extension $ref, Extension $new): void { static::assertEquals($ref, $new); } @@ -124,7 +124,7 @@ public function recoded(Extension $ref, Extension $new) * * @test */ - public function keyIdentifier(AuthorityKeyIdentifierExtension $ext) + public function keyIdentifier(AuthorityKeyIdentifierExtension $ext): void { static::assertEquals(self::KEY_ID, $ext->keyIdentifier()); } @@ -134,7 +134,7 @@ public function keyIdentifier(AuthorityKeyIdentifierExtension $ext) * * @test */ - public function issuer(AuthorityKeyIdentifierExtension $ext) + public function issuer(AuthorityKeyIdentifierExtension $ext): void { static::assertEquals(self::$_issuer, $ext->issuer()); } @@ -144,7 +144,7 @@ public function issuer(AuthorityKeyIdentifierExtension $ext) * * @test */ - public function serial(AuthorityKeyIdentifierExtension $ext) + public function serial(AuthorityKeyIdentifierExtension $ext): void { static::assertEquals(self::SERIAL, $ext->serial()); } @@ -154,9 +154,9 @@ public function serial(AuthorityKeyIdentifierExtension $ext) * * @test */ - public function extensions(AuthorityKeyIdentifierExtension $ext) + public function extensions(AuthorityKeyIdentifierExtension $ext): Extensions { - $extensions = new Extensions($ext); + $extensions = Extensions::create($ext); static::assertTrue($extensions->hasAuthorityKeyIdentifier()); return $extensions; } @@ -166,7 +166,7 @@ public function extensions(AuthorityKeyIdentifierExtension $ext) * * @test */ - public function fromExtensions(Extensions $exts) + public function fromExtensions(Extensions $exts): void { $ext = $exts->authorityKeyIdentifier(); static::assertInstanceOf(AuthorityKeyIdentifierExtension::class, $ext); @@ -175,7 +175,7 @@ public function fromExtensions(Extensions $exts) /** * @test */ - public function decodeIssuerXorSerialFail() + public function decodeIssuerXorSerialFail(): void { $seq = Sequence::create( ImplicitlyTaggedType::create(0, OctetString::create('')), @@ -192,9 +192,9 @@ public function decodeIssuerXorSerialFail() /** * @test */ - public function encodeIssuerXorSerialFail() + public function encodeIssuerXorSerialFail(): void { - $ext = new AuthorityKeyIdentifierExtension(false, '', null, 1); + $ext = AuthorityKeyIdentifierExtension::create(false, '', null, '1'); $this->expectException(LogicException::class); $ext->toASN1(); } @@ -202,9 +202,9 @@ public function encodeIssuerXorSerialFail() /** * @test */ - public function noKeyIdentifierFail() + public function noKeyIdentifierFail(): void { - $ext = new AuthorityKeyIdentifierExtension(false, null); + $ext = AuthorityKeyIdentifierExtension::create(false, null); $this->expectException(LogicException::class); $ext->keyIdentifier(); } @@ -212,9 +212,9 @@ public function noKeyIdentifierFail() /** * @test */ - public function noIssuerFail() + public function noIssuerFail(): void { - $ext = new AuthorityKeyIdentifierExtension(false, null); + $ext = AuthorityKeyIdentifierExtension::create(false, null); $this->expectException(LogicException::class); $ext->issuer(); } @@ -222,9 +222,9 @@ public function noIssuerFail() /** * @test */ - public function noSerialFail() + public function noSerialFail(): void { - $ext = new AuthorityKeyIdentifierExtension(false, null); + $ext = AuthorityKeyIdentifierExtension::create(false, null); $this->expectException(LogicException::class); $ext->serial(); } diff --git a/tests/X509/Unit/Certificate/Extension/BasicConstraintsTest.php b/tests/X509/Unit/Certificate/Extension/BasicConstraintsTest.php index a73eb4e8..a61c7350 100644 --- a/tests/X509/Unit/Certificate/Extension/BasicConstraintsTest.php +++ b/tests/X509/Unit/Certificate/Extension/BasicConstraintsTest.php @@ -21,7 +21,7 @@ final class BasicConstraintsTest extends TestCase */ public function create() { - $ext = new BasicConstraintsExtension(true, true, 3); + $ext = BasicConstraintsExtension::create(true, true, 3); static::assertInstanceOf(BasicConstraintsExtension::class, $ext); return $ext; } @@ -110,7 +110,7 @@ public function pathLen(BasicConstraintsExtension $ext) */ public function extensions(BasicConstraintsExtension $ext) { - $extensions = new Extensions($ext); + $extensions = Extensions::create($ext); static::assertTrue($extensions->hasBasicConstraints()); return $extensions; } @@ -131,7 +131,7 @@ public function fromExtensions(Extensions $exts) */ public function noPathLenFail() { - $ext = new BasicConstraintsExtension(false, false); + $ext = BasicConstraintsExtension::create(false, false); $this->expectException(LogicException::class); $ext->pathLen(); } diff --git a/tests/X509/Unit/Certificate/Extension/CRLDistributionPointTest.php b/tests/X509/Unit/Certificate/Extension/CRLDistributionPointTest.php index f8d63187..218ce21b 100644 --- a/tests/X509/Unit/Certificate/Extension/CRLDistributionPointTest.php +++ b/tests/X509/Unit/Certificate/Extension/CRLDistributionPointTest.php @@ -34,10 +34,10 @@ final class CRLDistributionPointTest extends TestCase */ public function createDistributionPoint() { - $name = new FullName(GeneralNames::create(UniformResourceIdentifier::create(self::DP_URI))); - $reasons = new ReasonFlags(ReasonFlags::PRIVILEGE_WITHDRAWN); + $name = FullName::create(GeneralNames::create(UniformResourceIdentifier::create(self::DP_URI))); + $reasons = ReasonFlags::create(ReasonFlags::PRIVILEGE_WITHDRAWN); $issuer = GeneralNames::create(DirectoryName::fromDNString(self::ISSUER_DN)); - $dp = new DistributionPoint($name, $reasons, $issuer); + $dp = DistributionPoint::create($name, $reasons, $issuer); static::assertInstanceOf(DistributionPoint::class, $dp); return $dp; } @@ -49,7 +49,7 @@ public function createDistributionPoint() */ public function create(DistributionPoint $dp) { - $ext = CRLDistributionPointsExtension::create(true, $dp, new DistributionPoint()); + $ext = CRLDistributionPointsExtension::create(true, $dp, DistributionPoint::create()); static::assertInstanceOf(CRLDistributionPointsExtension::class, $ext); return $ext; } @@ -188,7 +188,7 @@ public function dPIssuer(DistributionPoint $dp) */ public function extensions(CRLDistributionPointsExtension $ext) { - $extensions = new Extensions($ext); + $extensions = Extensions::create($ext); static::assertTrue($extensions->hasCRLDistributionPoints()); return $extensions; } diff --git a/tests/X509/Unit/Certificate/Extension/CertPolicy/CPSQualifierTest.php b/tests/X509/Unit/Certificate/Extension/CertPolicy/CPSQualifierTest.php index ab9562ac..523b9023 100644 --- a/tests/X509/Unit/Certificate/Extension/CertPolicy/CPSQualifierTest.php +++ b/tests/X509/Unit/Certificate/Extension/CertPolicy/CPSQualifierTest.php @@ -20,7 +20,7 @@ final class CPSQualifierTest extends TestCase */ public function create() { - $qual = new CPSQualifier(self::URI); + $qual = CPSQualifier::create(self::URI); static::assertInstanceOf(CPSQualifier::class, $qual); return $qual; } diff --git a/tests/X509/Unit/Certificate/Extension/CertPolicy/DisplayTextTest.php b/tests/X509/Unit/Certificate/Extension/CertPolicy/DisplayTextTest.php index dab844a4..619f02a0 100644 --- a/tests/X509/Unit/Certificate/Extension/CertPolicy/DisplayTextTest.php +++ b/tests/X509/Unit/Certificate/Extension/CertPolicy/DisplayTextTest.php @@ -83,7 +83,7 @@ public function string(DisplayText $dt) */ public function encodeIA5String() { - $dt = new DisplayText('', Element::TYPE_IA5_STRING); + $dt = DisplayText::create('', Element::TYPE_IA5_STRING); static::assertInstanceOf(IA5String::class, $dt->toASN1()); } @@ -92,7 +92,7 @@ public function encodeIA5String() */ public function encodeVisibleString() { - $dt = new DisplayText('', Element::TYPE_VISIBLE_STRING); + $dt = DisplayText::create('', Element::TYPE_VISIBLE_STRING); static::assertInstanceOf(VisibleString::class, $dt->toASN1()); } @@ -101,7 +101,7 @@ public function encodeVisibleString() */ public function encodeBMPString() { - $dt = new DisplayText('', Element::TYPE_BMP_STRING); + $dt = DisplayText::create('', Element::TYPE_BMP_STRING); static::assertInstanceOf(BMPString::class, $dt->toASN1()); } @@ -110,7 +110,7 @@ public function encodeBMPString() */ public function encodeUTF8String() { - $dt = new DisplayText('', Element::TYPE_UTF8_STRING); + $dt = DisplayText::create('', Element::TYPE_UTF8_STRING); static::assertInstanceOf(UTF8String::class, $dt->toASN1()); } @@ -119,7 +119,7 @@ public function encodeUTF8String() */ public function encodeUnsupportedTypeFail() { - $dt = new DisplayText('', Element::TYPE_NULL); + $dt = DisplayText::create('', Element::TYPE_NULL); $this->expectException(UnexpectedValueException::class); $dt->toASN1(); } diff --git a/tests/X509/Unit/Certificate/Extension/CertPolicy/NoticeReferenceTest.php b/tests/X509/Unit/Certificate/Extension/CertPolicy/NoticeReferenceTest.php index 453c387c..ecf281fe 100644 --- a/tests/X509/Unit/Certificate/Extension/CertPolicy/NoticeReferenceTest.php +++ b/tests/X509/Unit/Certificate/Extension/CertPolicy/NoticeReferenceTest.php @@ -19,7 +19,7 @@ final class NoticeReferenceTest extends TestCase */ public function create() { - $ref = new NoticeReference(DisplayText::fromString('org'), 1, 2, 3); + $ref = NoticeReference::create(DisplayText::fromString('org'), 1, 2, 3); static::assertInstanceOf(NoticeReference::class, $ref); return $ref; } diff --git a/tests/X509/Unit/Certificate/Extension/CertPolicy/PolicyInformationTest.php b/tests/X509/Unit/Certificate/Extension/CertPolicy/PolicyInformationTest.php index 6b38f30a..0e9c49cc 100644 --- a/tests/X509/Unit/Certificate/Extension/CertPolicy/PolicyInformationTest.php +++ b/tests/X509/Unit/Certificate/Extension/CertPolicy/PolicyInformationTest.php @@ -25,7 +25,7 @@ final class PolicyInformationTest extends TestCase */ public function createWithCPS() { - $pi = new PolicyInformation(self::OID, new CPSQualifier('urn:test')); + $pi = PolicyInformation::create(self::OID, CPSQualifier::create('urn:test')); static::assertInstanceOf(PolicyInformation::class, $pi); return $pi; } @@ -144,7 +144,7 @@ public function userNoticeQualifierFail(PolicyInformation $pi) */ public function createWithNotice() { - $pi = new PolicyInformation(self::OID, new UserNoticeQualifier(DisplayText::fromString('notice'))); + $pi = PolicyInformation::create(self::OID, UserNoticeQualifier::create(DisplayText::fromString('notice'))); static::assertInstanceOf(PolicyInformation::class, $pi); return $pi; } @@ -175,10 +175,10 @@ public function userNoticeQualifier(PolicyInformation $pi) */ public function createWithMultiple() { - $pi = new PolicyInformation( + $pi = PolicyInformation::create( self::OID, - new CPSQualifier('urn:test'), - new UserNoticeQualifier(DisplayText::fromString('notice')) + CPSQualifier::create('urn:test'), + UserNoticeQualifier::create(DisplayText::fromString('notice')) ); static::assertInstanceOf(PolicyInformation::class, $pi); return $pi; @@ -250,7 +250,7 @@ public function iterator(PolicyInformation $pi) */ public function isAnyPolicy() { - $pi = new PolicyInformation(PolicyInformation::OID_ANY_POLICY); + $pi = PolicyInformation::create(PolicyInformation::OID_ANY_POLICY); static::assertTrue($pi->isAnyPolicy()); } } diff --git a/tests/X509/Unit/Certificate/Extension/CertPolicy/UserNoticeQualifierTest.php b/tests/X509/Unit/Certificate/Extension/CertPolicy/UserNoticeQualifierTest.php index 096ef8d7..98e5d7a7 100644 --- a/tests/X509/Unit/Certificate/Extension/CertPolicy/UserNoticeQualifierTest.php +++ b/tests/X509/Unit/Certificate/Extension/CertPolicy/UserNoticeQualifierTest.php @@ -21,9 +21,9 @@ final class UserNoticeQualifierTest extends TestCase */ public function create() { - $qual = new UserNoticeQualifier( + $qual = UserNoticeQualifier::create( DisplayText::fromString('test'), - new NoticeReference(DisplayText::fromString('org'), 1, 2, 3) + NoticeReference::create(DisplayText::fromString('org'), 1, 2, 3) ); static::assertInstanceOf(UserNoticeQualifier::class, $qual); return $qual; @@ -91,7 +91,7 @@ public function noticeRef(UserNoticeQualifier $qual) */ public function createEmpty() { - $qual = new UserNoticeQualifier(); + $qual = UserNoticeQualifier::create(); static::assertInstanceOf(UserNoticeQualifier::class, $qual); return $qual; } diff --git a/tests/X509/Unit/Certificate/Extension/CertificatePoliciesTest.php b/tests/X509/Unit/Certificate/Extension/CertificatePoliciesTest.php index 154e2133..c85bf5a5 100644 --- a/tests/X509/Unit/Certificate/Extension/CertificatePoliciesTest.php +++ b/tests/X509/Unit/Certificate/Extension/CertificatePoliciesTest.php @@ -38,7 +38,7 @@ final class CertificatePoliciesTest extends TestCase */ public function createCPS() { - $qual = new CPSQualifier('urn:test'); + $qual = CPSQualifier::create('urn:test'); static::assertInstanceOf(PolicyQualifierInfo::class, $qual); return $qual; } @@ -48,9 +48,9 @@ public function createCPS() */ public function createNotice() { - $qual = new UserNoticeQualifier( + $qual = UserNoticeQualifier::create( DisplayText::fromString('Notice'), - new NoticeReference(DisplayText::fromString(self::REF_ORG), 1, 2, 3) + NoticeReference::create(DisplayText::fromString(self::REF_ORG), 1, 2, 3) ); static::assertInstanceOf(PolicyQualifierInfo::class, $qual); return $qual; @@ -64,7 +64,7 @@ public function createNotice() */ public function createPolicyInfo(PolicyQualifierInfo $q1, PolicyQualifierInfo $q2) { - $info = new PolicyInformation(self::INFO_OID, $q1, $q2); + $info = PolicyInformation::create(self::INFO_OID, $q1, $q2); static::assertInstanceOf(PolicyInformation::class, $info); return $info; } @@ -76,7 +76,7 @@ public function createPolicyInfo(PolicyQualifierInfo $q1, PolicyQualifierInfo $q */ public function create(PolicyInformation $info) { - $ext = new CertificatePoliciesExtension(true, $info, new PolicyInformation('1.3.6.1.3.10')); + $ext = CertificatePoliciesExtension::create(true, $info, PolicyInformation::create('1.3.6.1.3.10')); static::assertInstanceOf(CertificatePoliciesExtension::class, $ext); return $ext; } @@ -179,7 +179,7 @@ public function getFail(CertificatePoliciesExtension $ext) */ public function hasAnyPolicy() { - $ext = new CertificatePoliciesExtension(true, new PolicyInformation(PolicyInformation::OID_ANY_POLICY)); + $ext = CertificatePoliciesExtension::create(true, PolicyInformation::create(PolicyInformation::OID_ANY_POLICY)); static::assertTrue($ext->hasAnyPolicy()); } @@ -188,7 +188,7 @@ public function hasAnyPolicy() */ public function anyPolicyFail() { - $ext = new CertificatePoliciesExtension(true, new PolicyInformation('1.3.6.1.3')); + $ext = CertificatePoliciesExtension::create(true, PolicyInformation::create('1.3.6.1.3')); $this->expectException(LogicException::class); $ext->anyPolicy(); } @@ -313,7 +313,7 @@ public function refNumbers(NoticeReference $ref) */ public function extensions(CertificatePoliciesExtension $ext) { - $extensions = new Extensions($ext); + $extensions = Extensions::create($ext); static::assertTrue($extensions->hasCertificatePolicies()); return $extensions; } @@ -334,7 +334,7 @@ public function fromExtensions(Extensions $exts) */ public function encodeEmptyFail() { - $ext = new CertificatePoliciesExtension(false); + $ext = CertificatePoliciesExtension::create(false); $this->expectException(LogicException::class); $ext->toASN1(); } diff --git a/tests/X509/Unit/Certificate/Extension/DistPoint/DistributionPointTest.php b/tests/X509/Unit/Certificate/Extension/DistPoint/DistributionPointTest.php index e99b9bc9..a784c802 100644 --- a/tests/X509/Unit/Certificate/Extension/DistPoint/DistributionPointTest.php +++ b/tests/X509/Unit/Certificate/Extension/DistPoint/DistributionPointTest.php @@ -28,9 +28,9 @@ final class DistributionPointTest extends TestCase */ public function createWithFullName() { - $dp = new DistributionPoint( + $dp = DistributionPoint::create( FullName::fromURI('urn:test'), - new ReasonFlags(ReasonFlags::KEY_COMPROMISE), + ReasonFlags::create(ReasonFlags::KEY_COMPROMISE), GeneralNames::create(DirectoryName::fromDNString('cn=Issuer')) ); static::assertInstanceOf(DistributionPoint::class, $dp); @@ -130,8 +130,10 @@ public function cRLIssuer(DistributionPoint $dp) */ public function createWithRelativeName() { - $dp = new DistributionPoint( - new RelativeName(new RDN(AttributeTypeAndValue::fromAttributeValue(CommonNameValue::create('Test')))) + $dp = DistributionPoint::create( + RelativeName::create( + RDN::create(AttributeTypeAndValue::fromAttributeValue(CommonNameValue::create('Test'))) + ) ); static::assertInstanceOf(DistributionPoint::class, $dp); return $dp; @@ -200,7 +202,7 @@ public function fullNameFail(DistributionPoint $dp) */ public function createEmpty() { - $dp = new DistributionPoint(); + $dp = DistributionPoint::create(); static::assertInstanceOf(DistributionPoint::class, $dp); return $dp; } diff --git a/tests/X509/Unit/Certificate/Extension/DistPoint/ReasonFlagsTest.php b/tests/X509/Unit/Certificate/Extension/DistPoint/ReasonFlagsTest.php index 6f50d531..d15e1c63 100644 --- a/tests/X509/Unit/Certificate/Extension/DistPoint/ReasonFlagsTest.php +++ b/tests/X509/Unit/Certificate/Extension/DistPoint/ReasonFlagsTest.php @@ -20,7 +20,7 @@ final class ReasonFlagsTest extends TestCase */ public function create() { - $reasons = new ReasonFlags( + $reasons = ReasonFlags::create( ReasonFlags::KEY_COMPROMISE | ReasonFlags::AFFILIATION_CHANGED | ReasonFlags::CESSATION_OF_OPERATION | ReasonFlags::PRIVILEGE_WITHDRAWN diff --git a/tests/X509/Unit/Certificate/Extension/DistPoint/RelativeNameTest.php b/tests/X509/Unit/Certificate/Extension/DistPoint/RelativeNameTest.php index c66be48a..f56f0379 100644 --- a/tests/X509/Unit/Certificate/Extension/DistPoint/RelativeNameTest.php +++ b/tests/X509/Unit/Certificate/Extension/DistPoint/RelativeNameTest.php @@ -22,7 +22,9 @@ final class RelativeNameTest extends TestCase */ public function create() { - $name = new RelativeName(new RDN(AttributeTypeAndValue::fromAttributeValue(CommonNameValue::create('Test')))); + $name = RelativeName::create( + RDN::create(AttributeTypeAndValue::fromAttributeValue(CommonNameValue::create('Test'))) + ); static::assertInstanceOf(RelativeName::class, $name); return $name; } diff --git a/tests/X509/Unit/Certificate/Extension/ExtendedKeyUsageTest.php b/tests/X509/Unit/Certificate/Extension/ExtendedKeyUsageTest.php index bd99f47f..7794940d 100644 --- a/tests/X509/Unit/Certificate/Extension/ExtendedKeyUsageTest.php +++ b/tests/X509/Unit/Certificate/Extension/ExtendedKeyUsageTest.php @@ -20,7 +20,7 @@ final class ExtendedKeyUsageTest extends TestCase */ public function create() { - $ext = new ExtendedKeyUsageExtension( + $ext = ExtendedKeyUsageExtension::create( true, ExtendedKeyUsageExtension::OID_SERVER_AUTH, ExtendedKeyUsageExtension::OID_CLIENT_AUTH @@ -149,7 +149,7 @@ public function iterator(ExtendedKeyUsageExtension $ext) */ public function extensions(ExtendedKeyUsageExtension $ext) { - $extensions = new Extensions($ext); + $extensions = Extensions::create($ext); static::assertTrue($extensions->hasExtendedKeyUsage()); return $extensions; } diff --git a/tests/X509/Unit/Certificate/Extension/ExtensionTest.php b/tests/X509/Unit/Certificate/Extension/ExtensionTest.php index 4a80c0a1..6f615718 100644 --- a/tests/X509/Unit/Certificate/Extension/ExtensionTest.php +++ b/tests/X509/Unit/Certificate/Extension/ExtensionTest.php @@ -19,7 +19,7 @@ final class ExtensionTest extends TestCase */ public function extensionName() { - $ext = new BasicConstraintsExtension(true, true); + $ext = BasicConstraintsExtension::create(true, true); static::assertEquals('basicConstraints', $ext->extensionName()); } @@ -28,7 +28,7 @@ public function extensionName() */ public function unknownExtensionName() { - $ext = new UnknownExtension('1.3.6.1.3', false, NullType::create()); + $ext = UnknownExtension::create('1.3.6.1.3', false, NullType::create()); static::assertEquals('1.3.6.1.3', $ext->extensionName()); } @@ -37,7 +37,7 @@ public function unknownExtensionName() */ public function toStringMethod() { - $ext = new BasicConstraintsExtension(true, true); + $ext = BasicConstraintsExtension::create(true, true); static::assertEquals('basicConstraints', $ext); } } diff --git a/tests/X509/Unit/Certificate/Extension/FreshestCRLTest.php b/tests/X509/Unit/Certificate/Extension/FreshestCRLTest.php index 826e281c..5d9ceba2 100644 --- a/tests/X509/Unit/Certificate/Extension/FreshestCRLTest.php +++ b/tests/X509/Unit/Certificate/Extension/FreshestCRLTest.php @@ -24,10 +24,10 @@ final class FreshestCRLTest extends TestCase public static function setUpBeforeClass(): void { - $name = new FullName(GeneralNames::create(UniformResourceIdentifier::create('urn:test'))); - $reasons = new ReasonFlags(ReasonFlags::PRIVILEGE_WITHDRAWN); + $name = FullName::create(GeneralNames::create(UniformResourceIdentifier::create('urn:test'))); + $reasons = ReasonFlags::create(ReasonFlags::PRIVILEGE_WITHDRAWN); $issuer = GeneralNames::create(DirectoryName::fromDNString('cn=Issuer')); - self::$_dp = new DistributionPoint($name, $reasons, $issuer); + self::$_dp = DistributionPoint::create($name, $reasons, $issuer); } public static function tearDownAfterClass(): void diff --git a/tests/X509/Unit/Certificate/Extension/InhibitAnyPolicyTest.php b/tests/X509/Unit/Certificate/Extension/InhibitAnyPolicyTest.php index 2b2f2ccc..6a1cba12 100644 --- a/tests/X509/Unit/Certificate/Extension/InhibitAnyPolicyTest.php +++ b/tests/X509/Unit/Certificate/Extension/InhibitAnyPolicyTest.php @@ -20,7 +20,7 @@ final class InhibitAnyPolicyTest extends TestCase */ public function create() { - $ext = new InhibitAnyPolicyExtension(true, 3); + $ext = InhibitAnyPolicyExtension::create(true, 3); static::assertInstanceOf(InhibitAnyPolicyExtension::class, $ext); return $ext; } @@ -99,7 +99,7 @@ public function skipCerts(InhibitAnyPolicyExtension $ext) */ public function extensions(InhibitAnyPolicyExtension $ext) { - $extensions = new Extensions($ext); + $extensions = Extensions::create($ext); static::assertTrue($extensions->hasInhibitAnyPolicy()); return $extensions; } diff --git a/tests/X509/Unit/Certificate/Extension/IssuerAlternativeNameTest.php b/tests/X509/Unit/Certificate/Extension/IssuerAlternativeNameTest.php index 91e3342f..9085c5d9 100644 --- a/tests/X509/Unit/Certificate/Extension/IssuerAlternativeNameTest.php +++ b/tests/X509/Unit/Certificate/Extension/IssuerAlternativeNameTest.php @@ -24,7 +24,10 @@ final class IssuerAlternativeNameTest extends TestCase */ public function create() { - $ext = new IssuerAlternativeNameExtension(true, GeneralNames::create(DirectoryName::fromDNString(self::DN))); + $ext = IssuerAlternativeNameExtension::create( + true, + GeneralNames::create(DirectoryName::fromDNString(self::DN)) + ); static::assertInstanceOf(IssuerAlternativeNameExtension::class, $ext); return $ext; } @@ -103,7 +106,7 @@ public function name(IssuerAlternativeNameExtension $ext) */ public function extensions(IssuerAlternativeNameExtension $ext) { - $extensions = new Extensions($ext); + $extensions = Extensions::create($ext); static::assertTrue($extensions->hasIssuerAlternativeName()); return $extensions; } diff --git a/tests/X509/Unit/Certificate/Extension/KeyUsageTest.php b/tests/X509/Unit/Certificate/Extension/KeyUsageTest.php index cf958cce..69e03981 100644 --- a/tests/X509/Unit/Certificate/Extension/KeyUsageTest.php +++ b/tests/X509/Unit/Certificate/Extension/KeyUsageTest.php @@ -20,7 +20,7 @@ final class KeyUsageTest extends TestCase */ public function create() { - $ext = new KeyUsageExtension( + $ext = KeyUsageExtension::create( true, KeyUsageExtension::DIGITAL_SIGNATURE | KeyUsageExtension::KEY_ENCIPHERMENT @@ -183,7 +183,7 @@ public function decipherOnly(KeyUsageExtension $ext) */ public function extensions(KeyUsageExtension $ext) { - $extensions = new Extensions($ext); + $extensions = Extensions::create($ext); static::assertTrue($extensions->hasKeyUsage()); return $extensions; } diff --git a/tests/X509/Unit/Certificate/Extension/NameConstraints/GeneralSubtreeTest.php b/tests/X509/Unit/Certificate/Extension/NameConstraints/GeneralSubtreeTest.php index 41f044a1..ff632bb2 100644 --- a/tests/X509/Unit/Certificate/Extension/NameConstraints/GeneralSubtreeTest.php +++ b/tests/X509/Unit/Certificate/Extension/NameConstraints/GeneralSubtreeTest.php @@ -23,7 +23,7 @@ final class GeneralSubtreeTest extends TestCase */ public function create() { - $subtree = new GeneralSubtree(UniformResourceIdentifier::create(self::URI)); + $subtree = GeneralSubtree::create(UniformResourceIdentifier::create(self::URI)); static::assertInstanceOf(GeneralSubtree::class, $subtree); return $subtree; } @@ -81,7 +81,7 @@ public function base(GeneralSubtree $subtree) */ public function createWithAll() { - $subtree = new GeneralSubtree(UniformResourceIdentifier::create(self::URI), 1, 3); + $subtree = GeneralSubtree::create(UniformResourceIdentifier::create(self::URI), 1, 3); static::assertInstanceOf(GeneralSubtree::class, $subtree); return $subtree; } @@ -130,7 +130,7 @@ public function recodedWithAll(GeneralSubtree $ref, GeneralSubtree $new) */ public function collidingTag() { - $subtree = new GeneralSubtree(RFC822Name::create('test')); + $subtree = GeneralSubtree::create(RFC822Name::create('test')); $asn1 = $subtree->toASN1(); $result = GeneralSubtree::fromASN1($asn1); static::assertInstanceOf(GeneralSubtree::class, $result); diff --git a/tests/X509/Unit/Certificate/Extension/NameConstraints/GeneralSubtreesTest.php b/tests/X509/Unit/Certificate/Extension/NameConstraints/GeneralSubtreesTest.php index 719afd87..d7dbc049 100644 --- a/tests/X509/Unit/Certificate/Extension/NameConstraints/GeneralSubtreesTest.php +++ b/tests/X509/Unit/Certificate/Extension/NameConstraints/GeneralSubtreesTest.php @@ -23,9 +23,9 @@ final class GeneralSubtreesTest extends TestCase */ public function create() { - $subtrees = new GeneralSubtrees( - new GeneralSubtree(UniformResourceIdentifier::create('.example.com')), - new GeneralSubtree(DirectoryName::fromDNString('cn=Test')) + $subtrees = GeneralSubtrees::create( + GeneralSubtree::create(UniformResourceIdentifier::create('.example.com')), + GeneralSubtree::create(DirectoryName::fromDNString('cn=Test')) ); static::assertInstanceOf(GeneralSubtrees::class, $subtrees); return $subtrees; @@ -116,7 +116,7 @@ public function decodeEmptyFail() */ public function encodeEmptyFail() { - $subtrees = new GeneralSubtrees(); + $subtrees = GeneralSubtrees::create(); $this->expectException(LogicException::class); $subtrees->toASN1(); } diff --git a/tests/X509/Unit/Certificate/Extension/NameConstraintsTest.php b/tests/X509/Unit/Certificate/Extension/NameConstraintsTest.php index fd39ff11..4e535af8 100644 --- a/tests/X509/Unit/Certificate/Extension/NameConstraintsTest.php +++ b/tests/X509/Unit/Certificate/Extension/NameConstraintsTest.php @@ -31,9 +31,9 @@ final class NameConstraintsTest extends TestCase */ public function createPermitted() { - $subtrees = new GeneralSubtrees( - new GeneralSubtree(UniformResourceIdentifier::create(self::PERMITTED_URI)), - new GeneralSubtree(DirectoryName::fromDNString(self::PERMITTED_DN)) + $subtrees = GeneralSubtrees::create( + GeneralSubtree::create(UniformResourceIdentifier::create(self::PERMITTED_URI)), + GeneralSubtree::create(DirectoryName::fromDNString(self::PERMITTED_DN)) ); static::assertInstanceOf(GeneralSubtrees::class, $subtrees); return $subtrees; @@ -44,7 +44,9 @@ public function createPermitted() */ public function createExcluded() { - $subtrees = new GeneralSubtrees(new GeneralSubtree(UniformResourceIdentifier::create(self::EXCLUDED_URI))); + $subtrees = GeneralSubtrees::create( + GeneralSubtree::create(UniformResourceIdentifier::create(self::EXCLUDED_URI)) + ); static::assertInstanceOf(GeneralSubtrees::class, $subtrees); return $subtrees; } @@ -57,7 +59,7 @@ public function createExcluded() */ public function create(GeneralSubtrees $permitted, GeneralSubtrees $excluded) { - $ext = new NameConstraintsExtension(true, $permitted, $excluded); + $ext = NameConstraintsExtension::create(true, $permitted, $excluded); static::assertInstanceOf(NameConstraintsExtension::class, $ext); return $ext; } @@ -205,7 +207,7 @@ public function excludedURI(GeneralSubtrees $subtrees) */ public function extensions(NameConstraintsExtension $ext) { - $extensions = new Extensions($ext); + $extensions = Extensions::create($ext); static::assertTrue($extensions->hasNameConstraints()); return $extensions; } @@ -226,7 +228,7 @@ public function fromExtensions(Extensions $exts) */ public function createEmpty() { - $ext = new NameConstraintsExtension(false); + $ext = NameConstraintsExtension::create(false); static::assertInstanceOf(NameConstraintsExtension::class, $ext); return $ext; } diff --git a/tests/X509/Unit/Certificate/Extension/NoRevocationAvailableTest.php b/tests/X509/Unit/Certificate/Extension/NoRevocationAvailableTest.php index 55c8b389..b281208f 100644 --- a/tests/X509/Unit/Certificate/Extension/NoRevocationAvailableTest.php +++ b/tests/X509/Unit/Certificate/Extension/NoRevocationAvailableTest.php @@ -19,7 +19,7 @@ final class NoRevocationAvailableTest extends TestCase */ public function create() { - $ext = new NoRevocationAvailableExtension(true); + $ext = NoRevocationAvailableExtension::create(true); static::assertInstanceOf(NoRevocationAvailableExtension::class, $ext); return $ext; } diff --git a/tests/X509/Unit/Certificate/Extension/PolicyConstraintsTest.php b/tests/X509/Unit/Certificate/Extension/PolicyConstraintsTest.php index b904d76a..06f643dd 100644 --- a/tests/X509/Unit/Certificate/Extension/PolicyConstraintsTest.php +++ b/tests/X509/Unit/Certificate/Extension/PolicyConstraintsTest.php @@ -21,7 +21,7 @@ final class PolicyConstraintsTest extends TestCase */ public function create() { - $ext = new PolicyConstraintsExtension(true, 2, 3); + $ext = PolicyConstraintsExtension::create(true, 2, 3); static::assertInstanceOf(PolicyConstraintsExtension::class, $ext); return $ext; } @@ -110,7 +110,7 @@ public function inhibitMapping(PolicyConstraintsExtension $ext) */ public function extensions(PolicyConstraintsExtension $ext) { - $extensions = new Extensions($ext); + $extensions = Extensions::create($ext); static::assertTrue($extensions->hasPolicyConstraints()); return $extensions; } @@ -131,7 +131,7 @@ public function fromExtensions(Extensions $exts) */ public function createEmpty() { - $ext = new PolicyConstraintsExtension(false); + $ext = PolicyConstraintsExtension::create(false); static::assertInstanceOf(PolicyConstraintsExtension::class, $ext); return $ext; } diff --git a/tests/X509/Unit/Certificate/Extension/PolicyMapping/PolicyMappingTest.php b/tests/X509/Unit/Certificate/Extension/PolicyMapping/PolicyMappingTest.php index e3e7e2fa..c2e80ca9 100644 --- a/tests/X509/Unit/Certificate/Extension/PolicyMapping/PolicyMappingTest.php +++ b/tests/X509/Unit/Certificate/Extension/PolicyMapping/PolicyMappingTest.php @@ -22,7 +22,7 @@ final class PolicyMappingTest extends TestCase */ public function create() { - $mapping = new PolicyMapping(self::ISSUER_POLICY, self::SUBJECT_POLICY); + $mapping = PolicyMapping::create(self::ISSUER_POLICY, self::SUBJECT_POLICY); static::assertInstanceOf(PolicyMapping::class, $mapping); return $mapping; } diff --git a/tests/X509/Unit/Certificate/Extension/PolicyMappingsTest.php b/tests/X509/Unit/Certificate/Extension/PolicyMappingsTest.php index ffabbc5e..78b52821 100644 --- a/tests/X509/Unit/Certificate/Extension/PolicyMappingsTest.php +++ b/tests/X509/Unit/Certificate/Extension/PolicyMappingsTest.php @@ -31,8 +31,8 @@ final class PolicyMappingsTest extends TestCase public function createMappings() { $mappings = [ - new PolicyMapping(self::ISSUER_POLICY_OID, self::SUBJECT_POLICY_OID), - new PolicyMapping('1.3.6.1.3.3', '1.3.6.1.3.4'), ]; + PolicyMapping::create(self::ISSUER_POLICY_OID, self::SUBJECT_POLICY_OID), + PolicyMapping::create('1.3.6.1.3.3', '1.3.6.1.3.4'), ]; static::assertInstanceOf(PolicyMapping::class, $mappings[0]); return $mappings; } @@ -44,7 +44,7 @@ public function createMappings() */ public function create(array $mappings) { - $ext = new PolicyMappingsExtension(true, ...$mappings); + $ext = PolicyMappingsExtension::create(true, ...$mappings); static::assertInstanceOf(PolicyMappingsExtension::class, $ext); return $ext; } @@ -198,9 +198,9 @@ public function hasAnyPolicyMapping(PolicyMappingsExtension $ext) */ public function hasAnyPolicyIssuer() { - $ext = new PolicyMappingsExtension( + $ext = PolicyMappingsExtension::create( false, - new PolicyMapping(PolicyInformation::OID_ANY_POLICY, self::SUBJECT_POLICY_OID) + PolicyMapping::create(PolicyInformation::OID_ANY_POLICY, self::SUBJECT_POLICY_OID) ); static::assertTrue($ext->hasAnyPolicyMapping()); } @@ -210,9 +210,9 @@ public function hasAnyPolicyIssuer() */ public function hasAnyPolicySubject() { - $ext = new PolicyMappingsExtension( + $ext = PolicyMappingsExtension::create( false, - new PolicyMapping(self::ISSUER_POLICY_OID, PolicyInformation::OID_ANY_POLICY) + PolicyMapping::create(self::ISSUER_POLICY_OID, PolicyInformation::OID_ANY_POLICY) ); static::assertTrue($ext->hasAnyPolicyMapping()); } @@ -224,7 +224,7 @@ public function hasAnyPolicySubject() */ public function extensions(PolicyMappingsExtension $ext) { - $extensions = new Extensions($ext); + $extensions = Extensions::create($ext); static::assertTrue($extensions->hasPolicyMappings()); return $extensions; } @@ -245,7 +245,7 @@ public function fromExtensions(Extensions $exts) */ public function encodeEmptyFail() { - $ext = new PolicyMappingsExtension(false); + $ext = PolicyMappingsExtension::create(false); $this->expectException(LogicException::class); $ext->toASN1(); } diff --git a/tests/X509/Unit/Certificate/Extension/SubjectAlternativeNameTest.php b/tests/X509/Unit/Certificate/Extension/SubjectAlternativeNameTest.php index 3a5b88c1..96008fa3 100644 --- a/tests/X509/Unit/Certificate/Extension/SubjectAlternativeNameTest.php +++ b/tests/X509/Unit/Certificate/Extension/SubjectAlternativeNameTest.php @@ -24,7 +24,10 @@ final class SubjectAlternativeNameTest extends TestCase */ public function create() { - $ext = new SubjectAlternativeNameExtension(true, GeneralNames::create(DirectoryName::fromDNString(self::DN))); + $ext = SubjectAlternativeNameExtension::create( + true, + GeneralNames::create(DirectoryName::fromDNString(self::DN)) + ); static::assertInstanceOf(SubjectAlternativeNameExtension::class, $ext); return $ext; } @@ -103,7 +106,7 @@ public function name(SubjectAlternativeNameExtension $ext) */ public function extensions(SubjectAlternativeNameExtension $ext) { - $extensions = new Extensions($ext); + $extensions = Extensions::create($ext); static::assertTrue($extensions->hasSubjectAlternativeName()); return $extensions; } diff --git a/tests/X509/Unit/Certificate/Extension/SubjectDirectoryAttributesTest.php b/tests/X509/Unit/Certificate/Extension/SubjectDirectoryAttributesTest.php index b5562ba3..0bd35075 100644 --- a/tests/X509/Unit/Certificate/Extension/SubjectDirectoryAttributesTest.php +++ b/tests/X509/Unit/Certificate/Extension/SubjectDirectoryAttributesTest.php @@ -33,7 +33,7 @@ public function create() { $cn = CommonNameValue::create(self::CN); $desc = DescriptionValue::create(self::DESC); - $ext = new SubjectDirectoryAttributesExtension(false, $cn->toAttribute(), $desc->toAttribute()); + $ext = SubjectDirectoryAttributesExtension::create(false, $cn->toAttribute(), $desc->toAttribute()); static::assertInstanceOf(SubjectDirectoryAttributesExtension::class, $ext); return $ext; } @@ -195,7 +195,7 @@ public function iterator(SubjectDirectoryAttributesExtension $ext) */ public function encodeEmptyFail() { - $ext = new SubjectDirectoryAttributesExtension(false); + $ext = SubjectDirectoryAttributesExtension::create(false); $this->expectException(LogicException::class); $ext->toASN1(); } diff --git a/tests/X509/Unit/Certificate/Extension/SubjectInformationAccessTest.php b/tests/X509/Unit/Certificate/Extension/SubjectInformationAccessTest.php index 1606973c..8c4152f6 100644 --- a/tests/X509/Unit/Certificate/Extension/SubjectInformationAccessTest.php +++ b/tests/X509/Unit/Certificate/Extension/SubjectInformationAccessTest.php @@ -21,13 +21,13 @@ final class SubjectInformationAccessTest extends TestCase */ public function create() { - $ext = new SubjectInformationAccessExtension( + $ext = SubjectInformationAccessExtension::create( false, - new SubjectAccessDescription( + SubjectAccessDescription::create( SubjectAccessDescription::OID_METHOD_CA_REPOSITORY, UniformResourceIdentifier::create('urn:test') ), - new SubjectAccessDescription( + SubjectAccessDescription::create( SubjectAccessDescription::OID_METHOD_TIME_STAMPING, UniformResourceIdentifier::create('https://ts.example.com/') ) diff --git a/tests/X509/Unit/Certificate/Extension/SubjectKeyIdentifierTest.php b/tests/X509/Unit/Certificate/Extension/SubjectKeyIdentifierTest.php index 6a0590ac..2dca2fee 100644 --- a/tests/X509/Unit/Certificate/Extension/SubjectKeyIdentifierTest.php +++ b/tests/X509/Unit/Certificate/Extension/SubjectKeyIdentifierTest.php @@ -22,7 +22,7 @@ final class SubjectKeyIdentifierTest extends TestCase */ public function create() { - $ext = new SubjectKeyIdentifierExtension(true, self::KEY_ID); + $ext = SubjectKeyIdentifierExtension::create(true, self::KEY_ID); static::assertInstanceOf(SubjectKeyIdentifierExtension::class, $ext); return $ext; } @@ -101,7 +101,7 @@ public function keyIdentifier(SubjectKeyIdentifierExtension $ext) */ public function extensions(SubjectKeyIdentifierExtension $ext) { - $extensions = new Extensions($ext); + $extensions = Extensions::create($ext); static::assertTrue($extensions->hasSubjectKeyIdentifier()); return $extensions; } diff --git a/tests/X509/Unit/Certificate/Extension/Target/TargetGroupTest.php b/tests/X509/Unit/Certificate/Extension/Target/TargetGroupTest.php index 6d5187d7..f4c1af1a 100644 --- a/tests/X509/Unit/Certificate/Extension/Target/TargetGroupTest.php +++ b/tests/X509/Unit/Certificate/Extension/Target/TargetGroupTest.php @@ -24,7 +24,7 @@ final class TargetGroupTest extends TestCase */ public function create() { - $target = new TargetGroup(UniformResourceIdentifier::create(self::URI)); + $target = TargetGroup::create(UniformResourceIdentifier::create(self::URI)); static::assertInstanceOf(TargetGroup::class, $target); return $target; } diff --git a/tests/X509/Unit/Certificate/Extension/Target/TargetNameTest.php b/tests/X509/Unit/Certificate/Extension/Target/TargetNameTest.php index f08c4cf8..c28ac1af 100644 --- a/tests/X509/Unit/Certificate/Extension/Target/TargetNameTest.php +++ b/tests/X509/Unit/Certificate/Extension/Target/TargetNameTest.php @@ -24,7 +24,7 @@ final class TargetNameTest extends TestCase */ public function create() { - $target = new TargetName(UniformResourceIdentifier::create(self::URI)); + $target = TargetName::create(UniformResourceIdentifier::create(self::URI)); static::assertInstanceOf(TargetName::class, $target); return $target; } diff --git a/tests/X509/Unit/Certificate/Extension/Target/TargetTest.php b/tests/X509/Unit/Certificate/Extension/Target/TargetTest.php index 6bf9aa78..77036a25 100644 --- a/tests/X509/Unit/Certificate/Extension/Target/TargetTest.php +++ b/tests/X509/Unit/Certificate/Extension/Target/TargetTest.php @@ -43,8 +43,8 @@ public function decodeUnsupportedTagFail() */ public function equals() { - $t1 = new TargetName(DNSName::create('n1')); - $t2 = new TargetName(DNSName::create('n1')); + $t1 = TargetName::create(DNSName::create('n1')); + $t2 = TargetName::create(DNSName::create('n1')); static::assertTrue($t1->equals($t2)); } @@ -53,8 +53,8 @@ public function equals() */ public function notEquals() { - $t1 = new TargetName(DNSName::create('n1')); - $t2 = new TargetName(DNSName::create('n2')); + $t1 = TargetName::create(DNSName::create('n1')); + $t2 = TargetName::create(DNSName::create('n2')); static::assertFalse($t1->equals($t2)); } @@ -63,8 +63,8 @@ public function notEquals() */ public function notEqualsDifferentEncoding() { - $t1 = new TargetName(DNSName::create('n1')); - $t2 = new TargetName(RFC822Name::create('n2')); + $t1 = TargetName::create(DNSName::create('n1')); + $t2 = TargetName::create(RFC822Name::create('n2')); static::assertFalse($t1->equals($t2)); } @@ -73,8 +73,8 @@ public function notEqualsDifferentEncoding() */ public function notEqualsDifferentType() { - $t1 = new TargetName(DNSName::create('n1')); - $t2 = new TargetGroup(DNSName::create('n1')); + $t1 = TargetName::create(DNSName::create('n1')); + $t2 = TargetGroup::create(DNSName::create('n1')); static::assertFalse($t1->equals($t2)); } } diff --git a/tests/X509/Unit/Certificate/Extension/Target/TargetsTest.php b/tests/X509/Unit/Certificate/Extension/Target/TargetsTest.php index 33cc5ebb..415bff5f 100644 --- a/tests/X509/Unit/Certificate/Extension/Target/TargetsTest.php +++ b/tests/X509/Unit/Certificate/Extension/Target/TargetsTest.php @@ -24,8 +24,8 @@ final class TargetsTest extends TestCase public static function setUpBeforeClass(): void { - self::$_name = new TargetName(UniformResourceIdentifier::create('urn:target')); - self::$_group = new TargetGroup(UniformResourceIdentifier::create('urn:group')); + self::$_name = TargetName::create(UniformResourceIdentifier::create('urn:target')); + self::$_group = TargetGroup::create(UniformResourceIdentifier::create('urn:group')); } public static function tearDownAfterClass(): void @@ -39,7 +39,7 @@ public static function tearDownAfterClass(): void */ public function create() { - $targets = new Targets(self::$_name, self::$_group); + $targets = Targets::create(self::$_name, self::$_group); static::assertInstanceOf(Targets::class, $targets); return $targets; } @@ -132,6 +132,6 @@ public function hasTarget(Targets $targets) */ public function hasNoTarget(Targets $targets) { - static::assertFalse($targets->hasTarget(new TargetName(DNSName::create('nope')))); + static::assertFalse($targets->hasTarget(TargetName::create(DNSName::create('nope')))); } } diff --git a/tests/X509/Unit/Certificate/Extension/TargetInformationTest.php b/tests/X509/Unit/Certificate/Extension/TargetInformationTest.php index 96a9d648..45e3b4d0 100644 --- a/tests/X509/Unit/Certificate/Extension/TargetInformationTest.php +++ b/tests/X509/Unit/Certificate/Extension/TargetInformationTest.php @@ -29,9 +29,9 @@ final class TargetInformationTest extends TestCase */ public function createTargets() { - $targets = new Targets( - new TargetName(DirectoryName::fromDNString(self::NAME_DN)), - new TargetGroup(DNSName::create(self::GROUP_DOMAIN)) + $targets = Targets::create( + TargetName::create(DirectoryName::fromDNString(self::NAME_DN)), + TargetGroup::create(DNSName::create(self::GROUP_DOMAIN)) ); static::assertInstanceOf(Targets::class, $targets); return $targets; @@ -44,7 +44,7 @@ public function createTargets() */ public function create(Targets $targets) { - $ext = new TargetInformationExtension(true, $targets); + $ext = TargetInformationExtension::create(true, $targets); static::assertInstanceOf(TargetInformationExtension::class, $ext); return $ext; } @@ -168,7 +168,7 @@ public function clone(TargetInformationExtension $ext) */ public function fromTargets() { - $ext = TargetInformationExtension::fromTargets(new TargetName(DirectoryName::fromDNString(self::NAME_DN))); + $ext = TargetInformationExtension::fromTargets(TargetName::create(DirectoryName::fromDNString(self::NAME_DN))); static::assertInstanceOf(TargetInformationExtension::class, $ext); } } diff --git a/tests/X509/Unit/Certificate/Extension/UnknownExtensionTest.php b/tests/X509/Unit/Certificate/Extension/UnknownExtensionTest.php index 35bc1e27..a3d59f5d 100644 --- a/tests/X509/Unit/Certificate/Extension/UnknownExtensionTest.php +++ b/tests/X509/Unit/Certificate/Extension/UnknownExtensionTest.php @@ -22,7 +22,7 @@ final class UnknownExtensionTest extends TestCase */ public function createWithDER() { - $ext = new UnknownExtension('1.3.6.1.3.1', true, NullType::create()); + $ext = UnknownExtension::create('1.3.6.1.3.1', true, NullType::create()); static::assertInstanceOf(UnknownExtension::class, $ext); return $ext; } @@ -68,7 +68,7 @@ public function extensionValueRaw(UnknownExtension $ext) public function extensionValueASN1(UnknownExtension $ext) { $cls = new ReflectionClass(UnknownExtension::class); - $mtd = $cls->getMethod('_valueASN1'); + $mtd = $cls->getMethod('valueASN1'); $mtd->setAccessible(true); $result = $mtd->invoke($ext); static::assertInstanceOf(Element::class, $result); diff --git a/tests/X509/Unit/Certificate/ExtensionsTest.php b/tests/X509/Unit/Certificate/ExtensionsTest.php index 52d1f0da..ef5e346b 100644 --- a/tests/X509/Unit/Certificate/ExtensionsTest.php +++ b/tests/X509/Unit/Certificate/ExtensionsTest.php @@ -22,9 +22,9 @@ final class ExtensionsTest extends TestCase */ public function create() { - $exts = new Extensions( - new UnknownExtension('1.3.6.1.3.1', true, DERData::create("\x05\x00")), - new UnknownExtension('1.3.6.1.3.2', true, DERData::create("\x05\x00")) + $exts = Extensions::create( + UnknownExtension::create('1.3.6.1.3.1', true, DERData::create("\x05\x00")), + UnknownExtension::create('1.3.6.1.3.2', true, DERData::create("\x05\x00")) ); static::assertInstanceOf(Extensions::class, $exts); return $exts; @@ -141,7 +141,7 @@ public function iterator(Extensions $exts) public function withExtensions(Extensions $exts) { static $oid = '1.3.6.1.3.3'; - $exts = $exts->withExtensions(new UnknownExtension($oid, true, DERData::create("\x05\x00"))); + $exts = $exts->withExtensions(UnknownExtension::create($oid, true, DERData::create("\x05\x00"))); static::assertTrue($exts->has($oid)); } } diff --git a/tests/X509/Unit/Certificate/TBSCertificateTest.php b/tests/X509/Unit/Certificate/TBSCertificateTest.php index 6e37222d..831b6298 100644 --- a/tests/X509/Unit/Certificate/TBSCertificateTest.php +++ b/tests/X509/Unit/Certificate/TBSCertificateTest.php @@ -58,7 +58,7 @@ public static function tearDownAfterClass(): void */ public function create() { - $tc = new TBSCertificate( + $tc = TBSCertificate::create( self::$_subject, self::$_privateKeyInfo->publicKeyInfo(), self::$_issuer, @@ -73,7 +73,7 @@ public function create() */ public function createWithAll() { - $tc = new TBSCertificate( + $tc = TBSCertificate::create( self::$_subject, self::$_privateKeyInfo->publicKeyInfo(), self::$_issuer, @@ -84,7 +84,7 @@ public function createWithAll() ->withSignature(SHA1WithRSAEncryptionAlgorithmIdentifier::create()) ->withIssuerUniqueID(UniqueIdentifier::fromString('issuer')) ->withSubjectUniqueID(UniqueIdentifier::fromString('subject')) - ->withAdditionalExtensions(new BasicConstraintsExtension(true, false)); + ->withAdditionalExtensions(BasicConstraintsExtension::create(true, false)); static::assertInstanceOf(TBSCertificate::class, $tc); return $tc; } @@ -344,7 +344,7 @@ public function withSubjectUniqueID(TBSCertificate $tc) */ public function withExtensions(TBSCertificate $tc) { - $tc = $tc->withExtensions(new Extensions()); + $tc = $tc->withExtensions(Extensions::create()); static::assertInstanceOf(TBSCertificate::class, $tc); } @@ -355,7 +355,7 @@ public function withExtensions(TBSCertificate $tc) */ public function withAdditionalExtensions(TBSCertificate $tc) { - $tc = $tc->withAdditionalExtensions(new UnknownExtension('1.3.6.1.3', false, NullType::create())); + $tc = $tc->withAdditionalExtensions(UnknownExtension::create('1.3.6.1.3', false, NullType::create())); static::assertInstanceOf(TBSCertificate::class, $tc); } diff --git a/tests/X509/Unit/Certificate/TimeTest.php b/tests/X509/Unit/Certificate/TimeTest.php index 5c63ba52..7e2c56c5 100644 --- a/tests/X509/Unit/Certificate/TimeTest.php +++ b/tests/X509/Unit/Certificate/TimeTest.php @@ -7,13 +7,10 @@ use DateTimeImmutable; use DateTimeZone; use PHPUnit\Framework\TestCase; -use ReflectionClass; use RuntimeException; -use SpomkyLabs\Pki\ASN1\Element; use SpomkyLabs\Pki\ASN1\Type\Primitive\GeneralizedTime; use SpomkyLabs\Pki\ASN1\Type\Primitive\UTCTime; use SpomkyLabs\Pki\X509\Certificate\Time; -use UnexpectedValueException; /** * @internal @@ -27,7 +24,7 @@ final class TimeTest extends TestCase /** * @test */ - public function create() + public function create(): Time { $time = Time::fromString(self::TIME); static::assertInstanceOf(Time::class, $time); @@ -39,7 +36,7 @@ public function create() * * @test */ - public function encode(Time $time) + public function encode(Time $time): string { $seq = $time->toASN1(); static::assertInstanceOf(UTCTime::class, $seq); @@ -53,7 +50,7 @@ public function encode(Time $time) * * @test */ - public function decode($der) + public function decode($der): Time { $time = Time::fromASN1(UTCTime::fromDER($der)); static::assertInstanceOf(Time::class, $time); @@ -66,7 +63,7 @@ public function decode($der) * * @test */ - public function recoded(Time $ref, Time $new) + public function recoded(Time $ref, Time $new): void { static::assertEquals($ref, $new); } @@ -76,7 +73,7 @@ public function recoded(Time $ref, Time $new) * * @test */ - public function time(Time $time) + public function time(Time $time): void { static::assertEquals(new DateTimeImmutable(self::TIME), $time->dateTime()); } @@ -84,7 +81,7 @@ public function time(Time $time) /** * @test */ - public function timezone() + public function timezone(): void { $time = Time::fromString(self::TIME, 'UTC'); static::assertEquals(new DateTimeImmutable(self::TIME, new DateTimeZone('UTC')), $time->dateTime()); @@ -93,7 +90,7 @@ public function timezone() /** * @test */ - public function createGeneralized() + public function createGeneralized(): Time { $time = Time::fromString(self::TIME_GEN, 'UTC'); static::assertInstanceOf(Time::class, $time); @@ -105,7 +102,7 @@ public function createGeneralized() * * @test */ - public function encodeGeneralized(Time $time) + public function encodeGeneralized(Time $time): string { $el = $time->toASN1(); static::assertInstanceOf(GeneralizedTime::class, $el); @@ -119,7 +116,7 @@ public function encodeGeneralized(Time $time) * * @test */ - public function decodeGeneralized($der) + public function decodeGeneralized($der): Time { $time = Time::fromASN1(GeneralizedTime::fromDER($der)); static::assertInstanceOf(Time::class, $time); @@ -132,7 +129,7 @@ public function decodeGeneralized($der) * * @test */ - public function recodedGeneralized(Time $ref, Time $new) + public function recodedGeneralized(Time $ref, Time $new): void { static::assertEquals($ref, $new); } @@ -140,32 +137,17 @@ public function recodedGeneralized(Time $ref, Time $new) /** * @test */ - public function decodeFractional() + public function decodeFractional(): void { $dt = DateTimeImmutable::createFromFormat('!Y-m-d H:i:s.u', '2050-01-01 12:00:00.500'); - $time = new Time($dt); + $time = Time::create($dt); static::assertInstanceOf(GeneralizedTime::class, $time->toASN1()); } - /** - * @depends create - * - * @test - */ - public function decodeUnknownTypeFail(Time $time) - { - $cls = new ReflectionClass($time); - $prop = $cls->getProperty('_type'); - $prop->setAccessible(true); - $prop->setValue($time, Element::TYPE_NULL); - $this->expectException(UnexpectedValueException::class); - $time->toASN1(); - } - /** * @test */ - public function invalidDateFail() + public function invalidDateFail(): void { $this->expectException(RuntimeException::class); Time::fromString('nope'); @@ -174,7 +156,7 @@ public function invalidDateFail() /** * @test */ - public function invalidTimezone() + public function invalidTimezone(): void { $this->expectException(RuntimeException::class); Time::fromString('now', 'fail'); diff --git a/tests/X509/Unit/CertificationPath/CertificationPathBuildingTest.php b/tests/X509/Unit/CertificationPath/CertificationPathBuildingTest.php index ba276865..680888cf 100644 --- a/tests/X509/Unit/CertificationPath/CertificationPathBuildingTest.php +++ b/tests/X509/Unit/CertificationPath/CertificationPathBuildingTest.php @@ -42,8 +42,8 @@ public static function tearDownAfterClass(): void */ public function buildPath() { - $builder = new CertificationPathBuilder(new CertificateBundle(self::$_ca)); - $path = $builder->shortestPathToTarget(self::$_cert, new CertificateBundle(self::$_interm)); + $builder = CertificationPathBuilder::create(CertificateBundle::create(self::$_ca)); + $path = $builder->shortestPathToTarget(self::$_cert, CertificateBundle::create(self::$_interm)); static::assertInstanceOf(CertificationPath::class, $path); return $path; } @@ -93,9 +93,9 @@ public function pathTarget(CertificationPath $path) */ public function buildPathFail() { - $builder = new CertificationPathBuilder(new CertificateBundle(self::$_ca)); + $builder = CertificationPathBuilder::create(CertificateBundle::create(self::$_ca)); $this->expectException(PathBuildingException::class); - $builder->shortestPathToTarget(self::$_cert, new CertificateBundle()); + $builder->shortestPathToTarget(self::$_cert, CertificateBundle::create()); } /** @@ -103,7 +103,7 @@ public function buildPathFail() */ public function buildSelfSigned() { - $builder = new CertificationPathBuilder(new CertificateBundle(self::$_ca)); + $builder = CertificationPathBuilder::create(CertificateBundle::create(self::$_ca)); $path = $builder->shortestPathToTarget(self::$_ca); static::assertCount(1, $path); } @@ -113,7 +113,7 @@ public function buildSelfSigned() */ public function buildLength2() { - $builder = new CertificationPathBuilder(new CertificateBundle(self::$_ca)); + $builder = CertificationPathBuilder::create(CertificateBundle::create(self::$_ca)); $path = $builder->shortestPathToTarget(self::$_interm); static::assertCount(2, $path); } @@ -123,8 +123,8 @@ public function buildLength2() */ public function buildWithCAInIntermediate() { - $builder = new CertificationPathBuilder(new CertificateBundle(self::$_ca)); - $path = $builder->shortestPathToTarget(self::$_cert, new CertificateBundle(self::$_ca, self::$_interm)); + $builder = CertificationPathBuilder::create(CertificateBundle::create(self::$_ca)); + $path = $builder->shortestPathToTarget(self::$_cert, CertificateBundle::create(self::$_ca, self::$_interm)); static::assertCount(3, $path); } @@ -133,8 +133,8 @@ public function buildWithCAInIntermediate() */ public function buildMultipleChoices() { - $builder = new CertificationPathBuilder(new CertificateBundle(self::$_ca, self::$_interm)); - $paths = $builder->allPathsToTarget(self::$_cert, new CertificateBundle(self::$_interm)); + $builder = CertificationPathBuilder::create(CertificateBundle::create(self::$_ca, self::$_interm)); + $paths = $builder->allPathsToTarget(self::$_cert, CertificateBundle::create(self::$_interm)); static::assertCount(2, $paths); static::assertContainsOnlyInstancesOf(CertificationPath::class, $paths); } @@ -144,8 +144,8 @@ public function buildMultipleChoices() */ public function buildShortest() { - $builder = new CertificationPathBuilder(new CertificateBundle(self::$_ca, self::$_interm)); - $path = $builder->shortestPathToTarget(self::$_cert, new CertificateBundle(self::$_interm)); + $builder = CertificationPathBuilder::create(CertificateBundle::create(self::$_ca, self::$_interm)); + $path = $builder->shortestPathToTarget(self::$_cert, CertificateBundle::create(self::$_interm)); static::assertCount(2, $path); } } diff --git a/tests/X509/Unit/CertificationPath/CertificationPathTest.php b/tests/X509/Unit/CertificationPath/CertificationPathTest.php index 939e0e30..819d5776 100644 --- a/tests/X509/Unit/CertificationPath/CertificationPathTest.php +++ b/tests/X509/Unit/CertificationPath/CertificationPathTest.php @@ -40,7 +40,7 @@ public static function tearDownAfterClass(): void */ public function create() { - $path = new CertificationPath(...self::$_certs); + $path = CertificationPath::create(...self::$_certs); static::assertInstanceOf(CertificationPath::class, $path); return $path; } @@ -89,7 +89,7 @@ public function fromTrustAnchorToTarget() $path = CertificationPath::fromTrustAnchorToTarget( self::$_certs[0], self::$_certs[2], - new CertificateBundle(...self::$_certs) + CertificateBundle::create(...self::$_certs) ); static::assertInstanceOf(CertificationPath::class, $path); } @@ -99,7 +99,7 @@ public function fromTrustAnchorToTarget() */ public function fromCertificateChain() { - $chain = new CertificateChain(...array_reverse(self::$_certs, false)); + $chain = CertificateChain::create(...array_reverse(self::$_certs, false)); $path = CertificationPath::fromCertificateChain($chain); static::assertInstanceOf(CertificationPath::class, $path); return $path; @@ -132,7 +132,7 @@ public function trustAnchor(CertificationPath $path) */ public function trustAnchorFail() { - $path = new CertificationPath(); + $path = CertificationPath::create(); $this->expectException(LogicException::class); $path->trustAnchorCertificate(); } @@ -153,7 +153,7 @@ public function endEntity(CertificationPath $path) */ public function endEntityFail() { - $path = new CertificationPath(); + $path = CertificationPath::create(); $this->expectException(LogicException::class); $path->endEntityCertificate(); } diff --git a/tests/X509/Unit/CertificationPath/CertificationPathValidationTest.php b/tests/X509/Unit/CertificationPath/CertificationPathValidationTest.php index 922cb3cb..762b56b7 100644 --- a/tests/X509/Unit/CertificationPath/CertificationPathValidationTest.php +++ b/tests/X509/Unit/CertificationPath/CertificationPathValidationTest.php @@ -30,7 +30,7 @@ public static function setUpBeforeClass(): void Certificate::fromPEM(PEM::fromFile(TEST_ASSETS_DIR . '/certs/acme-interm-ecdsa.pem')), Certificate::fromPEM(PEM::fromFile(TEST_ASSETS_DIR . '/certs/acme-ecdsa.pem')), ]; - self::$_path = new CertificationPath(...$certs); + self::$_path = CertificationPath::create(...$certs); } public static function tearDownAfterClass(): void @@ -97,7 +97,7 @@ public function validatePathLengthFail() public function noCertsFail() { $this->expectException(LogicException::class); - new PathValidator(Crypto::getDefault(), PathValidationConfig::defaultConfig()); + PathValidator::create(Crypto::getDefault(), PathValidationConfig::defaultConfig()); } /** @@ -106,7 +106,7 @@ public function noCertsFail() public function explicitTrustAnchor() { $config = PathValidationConfig::defaultConfig()->withTrustAnchor(self::$_path->certificates()[0]); - $validator = new PathValidator(Crypto::getDefault(), $config, ...self::$_path->certificates()); + $validator = PathValidator::create(Crypto::getDefault(), $config, ...self::$_path->certificates()); static::assertInstanceOf(PathValidationResult::class, $validator->validate()); } } diff --git a/tests/X509/Unit/CertificationPath/Policy/PolicyNodeTest.php b/tests/X509/Unit/CertificationPath/Policy/PolicyNodeTest.php index ccdb5b9b..9b9ac865 100644 --- a/tests/X509/Unit/CertificationPath/Policy/PolicyNodeTest.php +++ b/tests/X509/Unit/CertificationPath/Policy/PolicyNodeTest.php @@ -17,7 +17,7 @@ final class PolicyNodeTest extends TestCase */ public function create() { - $node = new PolicyNode('1.3.6.1.3', [], []); + $node = PolicyNode::create('1.3.6.1.3', [], []); static::assertInstanceOf(PolicyNode::class, $node); } @@ -26,7 +26,7 @@ public function create() */ public function hasChildWithPolicyMatch() { - $node = PolicyNode::anyPolicyNode()->addChild(new PolicyNode('1.3.6.1.3', [], [])); + $node = PolicyNode::anyPolicyNode()->addChild(PolicyNode::create('1.3.6.1.3', [], [])); static::assertTrue($node->hasChildWithValidPolicy('1.3.6.1.3')); } @@ -36,7 +36,7 @@ public function hasChildWithPolicyMatch() public function parent() { $root = PolicyNode::anyPolicyNode(); - $child = new PolicyNode('1.3.6.1.3', [], []); + $child = PolicyNode::create('1.3.6.1.3', [], []); $root->addChild($child); static::assertEquals($root, $child->parent()); } diff --git a/tests/X509/Unit/CertificationPath/Policy/PolicyTreeTest.php b/tests/X509/Unit/CertificationPath/Policy/PolicyTreeTest.php index 72e8e9d6..fb74b272 100644 --- a/tests/X509/Unit/CertificationPath/Policy/PolicyTreeTest.php +++ b/tests/X509/Unit/CertificationPath/Policy/PolicyTreeTest.php @@ -21,9 +21,9 @@ final class PolicyTreeTest extends TestCase */ public function nodesAtDepthNoRoot() { - $tree = new PolicyTree(PolicyNode::anyPolicyNode()); + $tree = PolicyTree::create(PolicyNode::anyPolicyNode()); $obj = new ReflectionClass($tree); - $prop = $obj->getProperty('_root'); + $prop = $obj->getProperty('root'); $prop->setAccessible(true); $prop->setValue($tree, null); static::assertEmpty($tree->policiesAtDepth(1)); @@ -36,12 +36,12 @@ public function nodesAtDepthNoRoot() */ public function validPolicyNodeSetNoRoot() { - $tree = new PolicyTree(PolicyNode::anyPolicyNode()); + $tree = PolicyTree::create(PolicyNode::anyPolicyNode()); $obj = new ReflectionClass($tree); - $prop = $obj->getProperty('_root'); + $prop = $obj->getProperty('root'); $prop->setAccessible(true); $prop->setValue($tree, null); - $mtd = $obj->getMethod('_validPolicyNodeSet'); + $mtd = $obj->getMethod('validPolicyNodeSet'); $mtd->setAccessible(true); static::assertEmpty($mtd->invoke($tree)); } @@ -53,12 +53,12 @@ public function validPolicyNodeSetNoRoot() */ public function pruneNoRoot() { - $tree = new PolicyTree(PolicyNode::anyPolicyNode()); + $tree = PolicyTree::create(PolicyNode::anyPolicyNode()); $obj = new ReflectionClass($tree); - $prop = $obj->getProperty('_root'); + $prop = $obj->getProperty('root'); $prop->setAccessible(true); $prop->setValue($tree, null); - $mtd = $obj->getMethod('_pruneTree'); + $mtd = $obj->getMethod('pruneTree'); $mtd->setAccessible(true); static::assertEquals(0, $mtd->invoke($tree, 0)); } diff --git a/tests/X509/Unit/Csr/Attribute/ExtensionRequestTest.php b/tests/X509/Unit/Csr/Attribute/ExtensionRequestTest.php index b19664af..89eaa7ee 100644 --- a/tests/X509/Unit/Csr/Attribute/ExtensionRequestTest.php +++ b/tests/X509/Unit/Csr/Attribute/ExtensionRequestTest.php @@ -22,7 +22,7 @@ final class ExtensionRequestTest extends TestCase */ public function create() { - $value = new ExtensionRequestValue(new Extensions()); + $value = ExtensionRequestValue::create(Extensions::create()); static::assertInstanceOf(ExtensionRequestValue::class, $value); return $value; } diff --git a/tests/X509/Unit/Csr/AttributesTest.php b/tests/X509/Unit/Csr/AttributesTest.php index df29169f..b62d92dc 100644 --- a/tests/X509/Unit/Csr/AttributesTest.php +++ b/tests/X509/Unit/Csr/AttributesTest.php @@ -25,7 +25,7 @@ final class AttributesTest extends TestCase */ public function create() { - $attribs = Attributes::fromAttributeValues(new ExtensionRequestValue(new Extensions())); + $attribs = Attributes::fromAttributeValues(ExtensionRequestValue::create(Extensions::create())); static::assertInstanceOf(Attributes::class, $attribs); return $attribs; } diff --git a/tests/X509/Unit/Csr/CertificationRequestInfoTest.php b/tests/X509/Unit/Csr/CertificationRequestInfoTest.php index 6a959446..91e49f89 100644 --- a/tests/X509/Unit/Csr/CertificationRequestInfoTest.php +++ b/tests/X509/Unit/Csr/CertificationRequestInfoTest.php @@ -39,10 +39,13 @@ public static function setUpBeforeClass(): void { self::$_subject = Name::fromString('cn=Subject'); self::$_privateKeyInfo = PrivateKeyInfo::fromPEM(PEM::fromFile(TEST_ASSETS_DIR . '/rsa/private_key.pem')); - $extensions = new Extensions( - new SubjectAlternativeNameExtension(true, GeneralNames::create(DirectoryName::fromDNString(self::SAN_DN))) + $extensions = Extensions::create( + SubjectAlternativeNameExtension::create( + true, + GeneralNames::create(DirectoryName::fromDNString(self::SAN_DN)) + ) ); - self::$_attribs = Attributes::fromAttributeValues(new ExtensionRequestValue($extensions)); + self::$_attribs = Attributes::fromAttributeValues(ExtensionRequestValue::create($extensions)); } public static function tearDownAfterClass(): void @@ -58,7 +61,7 @@ public static function tearDownAfterClass(): void public function create() { $pkinfo = self::$_privateKeyInfo->publicKeyInfo(); - $cri = new CertificationRequestInfo(self::$_subject, $pkinfo); + $cri = CertificationRequestInfo::create(self::$_subject, $pkinfo); $cri = $cri->withAttributes(self::$_attribs); static::assertInstanceOf(CertificationRequestInfo::class, $cri); return $cri; @@ -140,7 +143,7 @@ public function withSubject(CertificationRequestInfo $cri) */ public function withExtensionRequest(CertificationRequestInfo $cri) { - $cri = $cri->withExtensionRequest(new Extensions()); + $cri = $cri->withExtensionRequest(Extensions::create()); static::assertTrue($cri->attributes()->hasExtensionRequest()); } @@ -149,8 +152,8 @@ public function withExtensionRequest(CertificationRequestInfo $cri) */ public function withExtensionRequestWithoutAttributes() { - $cri = new CertificationRequestInfo(self::$_subject, self::$_privateKeyInfo->publicKeyInfo()); - $cri = $cri->withExtensionRequest(new Extensions()); + $cri = CertificationRequestInfo::create(self::$_subject, self::$_privateKeyInfo->publicKeyInfo()); + $cri = $cri->withExtensionRequest(Extensions::create()); static::assertTrue($cri->attributes()->hasExtensionRequest()); } @@ -182,7 +185,7 @@ public function attribs(CertificationRequestInfo $cri) */ public function noAttributesFail() { - $cri = new CertificationRequestInfo(self::$_subject, self::$_privateKeyInfo->publicKeyInfo()); + $cri = CertificationRequestInfo::create(self::$_subject, self::$_privateKeyInfo->publicKeyInfo()); $this->expectException(LogicException::class); $cri->attributes(); } diff --git a/tests/X509/Unit/Csr/CertificationRequestTest.php b/tests/X509/Unit/Csr/CertificationRequestTest.php index 68246887..8b5dae81 100644 --- a/tests/X509/Unit/Csr/CertificationRequestTest.php +++ b/tests/X509/Unit/Csr/CertificationRequestTest.php @@ -45,12 +45,12 @@ public static function tearDownAfterClass(): void public function create() { $pkinfo = self::$_privateKeyInfo->publicKeyInfo(); - $cri = new CertificationRequestInfo(self::$_subject, $pkinfo); + $cri = CertificationRequestInfo::create(self::$_subject, $pkinfo); $data = $cri->toASN1() ->toDER(); $algo = SHA256WithRSAEncryptionAlgorithmIdentifier::create(); $signature = Crypto::getDefault()->sign($data, self::$_privateKeyInfo, $algo); - $cr = new CertificationRequest($cri, $algo, $signature); + $cr = CertificationRequest::create($cri, $algo, $signature); static::assertInstanceOf(CertificationRequest::class, $cr); return $cr; } diff --git a/tests/X509/Unit/GeneralName/IPv4AddressNameTest.php b/tests/X509/Unit/GeneralName/IPv4AddressNameTest.php index 7211ca83..25e2fb08 100644 --- a/tests/X509/Unit/GeneralName/IPv4AddressNameTest.php +++ b/tests/X509/Unit/GeneralName/IPv4AddressNameTest.php @@ -26,9 +26,9 @@ final class IPv4AddressNameTest extends TestCase /** * @test */ - public function create() + public function create(): IPv4Address { - $ip = new IPv4Address(self::ADDR); + $ip = IPv4Address::create(self::ADDR); static::assertInstanceOf(IPAddress::class, $ip); return $ip; } @@ -98,7 +98,7 @@ public function address(IPAddress $ip) */ public function createWithMask() { - $ip = new IPv4Address(self::ADDR, self::MASK); + $ip = IPv4Address::create(self::ADDR, self::MASK); static::assertInstanceOf(IPAddress::class, $ip); return $ip; } diff --git a/tests/X509/Unit/GeneralName/IPv6AddressNameTest.php b/tests/X509/Unit/GeneralName/IPv6AddressNameTest.php index d02c1235..38312b2e 100644 --- a/tests/X509/Unit/GeneralName/IPv6AddressNameTest.php +++ b/tests/X509/Unit/GeneralName/IPv6AddressNameTest.php @@ -28,7 +28,7 @@ final class IPv6AddressNameTest extends TestCase public function create() { // @todo implement compressed form handling - $ip = new IPv6Address(self::ADDR); + $ip = IPv6Address::create(self::ADDR); static::assertInstanceOf(IPAddress::class, $ip); return $ip; } @@ -98,7 +98,7 @@ public function iPv6(IPAddress $ip) */ public function createWithMask() { - $ip = new IPv6Address(self::ADDR, self::MASK); + $ip = IPv6Address::create(self::ADDR, self::MASK); static::assertInstanceOf(IPAddress::class, $ip); return $ip; } diff --git a/tests/assets/ac/make-ac.php b/tests/assets/ac/make-ac.php index 1fffbbf1..06001ff6 100644 --- a/tests/assets/ac/make-ac.php +++ b/tests/assets/ac/make-ac.php @@ -42,18 +42,18 @@ // load AC holder certificate $holder_cert = Certificate::fromPEM(PEM::fromFile(dirname(__DIR__) . '/certs/acme-ecdsa.pem')); -$holder = new Holder( +$holder = Holder::create( IssuerSerial::fromPKC($holder_cert), GeneralNames::create(DirectoryName::create($holder_cert->tbsCertificate()->subject())) ); -$issuer = new V2Form(GeneralNames::create(DirectoryName::create($issuer_cert->tbsCertificate()->subject()))); +$issuer = V2Form::create(GeneralNames::create(DirectoryName::create($issuer_cert->tbsCertificate()->subject()))); $validity = AttCertValidityPeriod::fromStrings('2016-01-01 12:00:00', '2016-03-01 12:00:00', 'UTC'); $authinfo_attr = AuthenticationInfoAttributeValue::create( UniformResourceIdentifier::create('urn:service'), DirectoryName::fromDNString('cn=username'), 'password' ); -$authid_attr = new AccessIdentityAttributeValue( +$authid_attr = AccessIdentityAttributeValue::create( UniformResourceIdentifier::create('urn:service'), DirectoryName::fromDNString('cn=username') ); @@ -61,8 +61,8 @@ $charge_attr = $charge_attr->withPolicyAuthority(GeneralNames::create(DirectoryName::fromDNString('cn=ACME Ltd.'))); $group_attr = GroupAttributeValue::create(IetfAttrValue::fromString('group1'), IetfAttrValue::fromString('group2')); $role_attr = Attribute::fromAttributeValues( - new RoleAttributeValue(UniformResourceIdentifier::create('urn:role1')), - new RoleAttributeValue(UniformResourceIdentifier::create('urn:role2')) + RoleAttributeValue::create(UniformResourceIdentifier::create('urn:role1')), + RoleAttributeValue::create(UniformResourceIdentifier::create('urn:role2')) ); $attribs = Attributes::fromAttributeValues( $authinfo_attr, @@ -70,18 +70,18 @@ $charge_attr, $group_attr )->withAdditional($role_attr); -$aki_ext = new AuthorityKeyIdentifierExtension(false, $issuer_public_key->keyIdentifier()); -$ti_ext = new TargetInformationExtension( +$aki_ext = AuthorityKeyIdentifierExtension::create(false, $issuer_public_key->keyIdentifier()); +$ti_ext = TargetInformationExtension::create( true, - new Targets( - new TargetName(UniformResourceIdentifier::create('urn:test')), - new TargetName(DNSName::create('*.example.com')) + Targets::create( + TargetName::create(UniformResourceIdentifier::create('urn:test')), + TargetName::create(DNSName::create('*.example.com')) ), - new Targets(new TargetName(UniformResourceIdentifier::create('urn:another'))) + Targets::create(TargetName::create(UniformResourceIdentifier::create('urn:another'))) ); -$nra_ext = new NoRevocationAvailableExtension(false); -$extensions = new Extensions($aki_ext, $nra_ext, $ti_ext); -$aci = new AttributeCertificateInfo($holder, $issuer, $validity, $attribs); +$nra_ext = NoRevocationAvailableExtension::create(false); +$extensions = Extensions::create($aki_ext, $nra_ext, $ti_ext); +$aci = AttributeCertificateInfo::create($holder, $issuer, $validity, $attribs); $aci = $aci->withSerialNumber(0xbadcafe); $aci = $aci->withExtensions($extensions); $ac = $aci->sign(SHA256WithRSAEncryptionAlgorithmIdentifier::create(), $issuer_private_key);