get(self::DATA_N); } public function e(): string { return $this->get(self::DATA_E); } public function d(): string { Assertion::true($this->isPrivate(), 'The key is not private.'); return $this->get(self::DATA_D); } public function p(): string { Assertion::true($this->isPrivate(), 'The key is not private.'); return $this->get(self::DATA_P); } public function q(): string { Assertion::true($this->isPrivate(), 'The key is not private.'); return $this->get(self::DATA_Q); } public function dP(): string { Assertion::true($this->isPrivate(), 'The key is not private.'); return $this->get(self::DATA_DP); } public function dQ(): string { Assertion::true($this->isPrivate(), 'The key is not private.'); return $this->get(self::DATA_DQ); } public function QInv(): string { Assertion::true($this->isPrivate(), 'The key is not private.'); return $this->get(self::DATA_QI); } public function other(): array { Assertion::true($this->isPrivate(), 'The key is not private.'); return $this->get(self::DATA_OTHER); } public function rI(): string { Assertion::true($this->isPrivate(), 'The key is not private.'); return $this->get(self::DATA_RI); } public function dI(): string { Assertion::true($this->isPrivate(), 'The key is not private.'); return $this->get(self::DATA_DI); } public function tI(): string { Assertion::true($this->isPrivate(), 'The key is not private.'); return $this->get(self::DATA_TI); } public function hasPrimes(): bool { return $this->has(self::DATA_P) && $this->has(self::DATA_Q); } public function primes(): array { return [ $this->p(), $this->q(), ]; } public function hasExponents(): bool { return $this->has(self::DATA_DP) && $this->has(self::DATA_DQ); } public function exponents(): array { return [ $this->dP(), $this->dQ(), ]; } public function hasCoefficient(): bool { return $this->has(self::DATA_QI); } public function isPublic(): bool { return !$this->isPrivate(); } public function isPrivate(): bool { return array_key_exists(self::DATA_D, $this->getData()); } public function asPem(): string { Assertion::false($this->isPrivate(), 'Unsupported for private keys.'); $bitSring = new Sequence( new Integer($this->fromBase64ToInteger($this->n())), new Integer($this->fromBase64ToInteger($this->e())) ); $der = new Sequence( new Sequence( new ObjectIdentifier('1.2.840.113549.1.1.1'), new NullObject() ), new BitString(bin2hex($bitSring->getBinary())) ); return $this->pem('PUBLIC KEY', $der->getBinary()); } private function fromBase64ToInteger(string $value): string { $hex = current(unpack('H*', $value)); return BigInteger::fromBase($hex, 16)->toBase(10); } private function pem(string $type, string $der): string { return sprintf("-----BEGIN %s-----\n", mb_strtoupper($type)). chunk_split(base64_encode($der), 64, "\n"). sprintf("-----END %s-----\n", mb_strtoupper($type)); } }