installed plugin WP-WebAuthn
version 1.2.8
This commit is contained in:
307
wp-content/plugins/wp-webauthn/vendor/web-token/jwt-key-mgmt/KeyConverter/ECKey.php
vendored
Normal file
307
wp-content/plugins/wp-webauthn/vendor/web-token/jwt-key-mgmt/KeyConverter/ECKey.php
vendored
Normal file
@ -0,0 +1,307 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* Copyright (c) 2014-2020 Spomky-Labs
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Jose\Component\KeyManagement\KeyConverter;
|
||||
|
||||
use function array_key_exists;
|
||||
use Base64Url\Base64Url;
|
||||
use function count;
|
||||
use FG\ASN1\ASNObject;
|
||||
use FG\ASN1\Exception\ParserException;
|
||||
use FG\ASN1\ExplicitlyTaggedObject;
|
||||
use FG\ASN1\Universal\BitString;
|
||||
use FG\ASN1\Universal\Integer;
|
||||
use FG\ASN1\Universal\ObjectIdentifier;
|
||||
use FG\ASN1\Universal\OctetString;
|
||||
use FG\ASN1\Universal\Sequence;
|
||||
use InvalidArgumentException;
|
||||
use function is_array;
|
||||
use function is_string;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
class ECKey
|
||||
{
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $values = [];
|
||||
|
||||
private function __construct(array $data)
|
||||
{
|
||||
$this->loadJWK($data);
|
||||
}
|
||||
|
||||
public static function createFromPEM(string $pem): self
|
||||
{
|
||||
$data = self::loadPEM($pem);
|
||||
|
||||
return new self($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ECKey $private
|
||||
*
|
||||
* @return ECKey
|
||||
*/
|
||||
public static function toPublic(self $private): self
|
||||
{
|
||||
$data = $private->toArray();
|
||||
if (array_key_exists('d', $data)) {
|
||||
unset($data['d']);
|
||||
}
|
||||
|
||||
return new self($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function toArray()
|
||||
{
|
||||
return $this->values;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws InvalidArgumentException if the key cannot be loaded
|
||||
* @throws ParserException if the key cannot be loaded
|
||||
*/
|
||||
private static function loadPEM(string $data): array
|
||||
{
|
||||
$data = base64_decode(preg_replace('#-.*-|\r|\n#', '', $data), true);
|
||||
$asnObject = ASNObject::fromBinary($data);
|
||||
if (!$asnObject instanceof Sequence) {
|
||||
throw new InvalidArgumentException('Unable to load the key.');
|
||||
}
|
||||
$children = $asnObject->getChildren();
|
||||
if (self::isPKCS8($children)) {
|
||||
$children = self::loadPKCS8($children);
|
||||
}
|
||||
|
||||
if (4 === count($children)) {
|
||||
return self::loadPrivatePEM($children);
|
||||
}
|
||||
if (2 === count($children)) {
|
||||
return self::loadPublicPEM($children);
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException('Unable to load the key.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ASNObject[] $children
|
||||
*
|
||||
* @throws InvalidArgumentException if the key cannot be loaded
|
||||
* @throws ParserException if the key cannot be loaded
|
||||
*/
|
||||
private static function loadPKCS8(array $children): array
|
||||
{
|
||||
$binary = hex2bin($children[2]->getContent());
|
||||
$asnObject = ASNObject::fromBinary($binary);
|
||||
if (!$asnObject instanceof Sequence) {
|
||||
throw new InvalidArgumentException('Unable to load the key.');
|
||||
}
|
||||
|
||||
return $asnObject->getChildren();
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws InvalidArgumentException if the key cannot be loaded
|
||||
*/
|
||||
private static function loadPublicPEM(array $children): array
|
||||
{
|
||||
if (!$children[0] instanceof Sequence) {
|
||||
throw new InvalidArgumentException('Unsupported key type.');
|
||||
}
|
||||
|
||||
$sub = $children[0]->getChildren();
|
||||
if (!$sub[0] instanceof ObjectIdentifier) {
|
||||
throw new InvalidArgumentException('Unsupported key type.');
|
||||
}
|
||||
if ('1.2.840.10045.2.1' !== $sub[0]->getContent()) {
|
||||
throw new InvalidArgumentException('Unsupported key type.');
|
||||
}
|
||||
if (!$sub[1] instanceof ObjectIdentifier) {
|
||||
throw new InvalidArgumentException('Unsupported key type.');
|
||||
}
|
||||
if (!$children[1] instanceof BitString) {
|
||||
throw new InvalidArgumentException('Unable to load the key.');
|
||||
}
|
||||
|
||||
$bits = $children[1]->getContent();
|
||||
$bits_length = mb_strlen($bits, '8bit');
|
||||
if (0 !== mb_strpos($bits, '04', 0, '8bit')) {
|
||||
throw new InvalidArgumentException('Unsupported key type');
|
||||
}
|
||||
|
||||
$values = ['kty' => 'EC'];
|
||||
$values['crv'] = self::getCurve($sub[1]->getContent());
|
||||
|
||||
$xBin = hex2bin(mb_substr($bits, 2, ($bits_length - 2) / 2, '8bit'));
|
||||
$yBin = hex2bin(mb_substr($bits, (int) (($bits_length - 2) / 2 + 2), ($bits_length - 2) / 2, '8bit'));
|
||||
if (!is_string($xBin) || !is_string($yBin)) {
|
||||
throw new InvalidArgumentException('Unable to load the key.');
|
||||
}
|
||||
|
||||
$values['x'] = Base64Url::encode($xBin);
|
||||
$values['y'] = Base64Url::encode($yBin);
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws InvalidArgumentException if the OID is not supported
|
||||
*/
|
||||
private static function getCurve(string $oid): string
|
||||
{
|
||||
$curves = self::getSupportedCurves();
|
||||
$curve = array_search($oid, $curves, true);
|
||||
if (!is_string($curve)) {
|
||||
throw new InvalidArgumentException('Unsupported OID.');
|
||||
}
|
||||
|
||||
return $curve;
|
||||
}
|
||||
|
||||
private static function getSupportedCurves(): array
|
||||
{
|
||||
return [
|
||||
'P-256' => '1.2.840.10045.3.1.7',
|
||||
'P-384' => '1.3.132.0.34',
|
||||
'P-521' => '1.3.132.0.35',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws InvalidArgumentException if the key cannot be loaded
|
||||
*/
|
||||
private static function verifyVersion(ASNObject $children): void
|
||||
{
|
||||
if (!$children instanceof Integer || '1' !== $children->getContent()) {
|
||||
throw new InvalidArgumentException('Unable to load the key.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws InvalidArgumentException if the key cannot be loaded
|
||||
*/
|
||||
private static function getXAndY(ASNObject $children, string &$x, string &$y): void
|
||||
{
|
||||
if (!$children instanceof ExplicitlyTaggedObject || !is_array($children->getContent())) {
|
||||
throw new InvalidArgumentException('Unable to load the key.');
|
||||
}
|
||||
if (!$children->getContent()[0] instanceof BitString) {
|
||||
throw new InvalidArgumentException('Unable to load the key.');
|
||||
}
|
||||
|
||||
$bits = $children->getContent()[0]->getContent();
|
||||
$bits_length = mb_strlen($bits, '8bit');
|
||||
|
||||
if (0 !== mb_strpos($bits, '04', 0, '8bit')) {
|
||||
throw new InvalidArgumentException('Unsupported key type');
|
||||
}
|
||||
|
||||
$x = mb_substr($bits, 2, (int) (($bits_length - 2) / 2), '8bit');
|
||||
$y = mb_substr($bits, (int) (($bits_length - 2) / 2 + 2), (int) (($bits_length - 2) / 2), '8bit');
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws InvalidArgumentException if the key cannot be loaded
|
||||
*/
|
||||
private static function getD(ASNObject $children): string
|
||||
{
|
||||
if (!$children instanceof OctetString) {
|
||||
throw new InvalidArgumentException('Unable to load the key.');
|
||||
}
|
||||
|
||||
return $children->getContent();
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws InvalidArgumentException if the key cannot be loaded
|
||||
*/
|
||||
private static function loadPrivatePEM(array $children): array
|
||||
{
|
||||
self::verifyVersion($children[0]);
|
||||
$x = '';
|
||||
$y = '';
|
||||
$d = self::getD($children[1]);
|
||||
self::getXAndY($children[3], $x, $y);
|
||||
|
||||
if (!$children[2] instanceof ExplicitlyTaggedObject || !is_array($children[2]->getContent())) {
|
||||
throw new InvalidArgumentException('Unable to load the key.');
|
||||
}
|
||||
if (!$children[2]->getContent()[0] instanceof ObjectIdentifier) {
|
||||
throw new InvalidArgumentException('Unable to load the key.');
|
||||
}
|
||||
|
||||
$curve = $children[2]->getContent()[0]->getContent();
|
||||
$dBin = hex2bin($d);
|
||||
$xBin = hex2bin($x);
|
||||
$yBin = hex2bin($y);
|
||||
if (!is_string($dBin) || !is_string($xBin) || !is_string($yBin)) {
|
||||
throw new InvalidArgumentException('Unable to load the key.');
|
||||
}
|
||||
|
||||
$values = ['kty' => 'EC'];
|
||||
$values['crv'] = self::getCurve($curve);
|
||||
$values['d'] = Base64Url::encode($dBin);
|
||||
$values['x'] = Base64Url::encode($xBin);
|
||||
$values['y'] = Base64Url::encode($yBin);
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ASNObject[] $children
|
||||
*/
|
||||
private static function isPKCS8(array $children): bool
|
||||
{
|
||||
if (3 !== count($children)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$classes = [0 => Integer::class, 1 => Sequence::class, 2 => OctetString::class];
|
||||
foreach ($classes as $k => $class) {
|
||||
if (!$children[$k] instanceof $class) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws InvalidArgumentException if the key is invalid
|
||||
*/
|
||||
private function loadJWK(array $jwk): void
|
||||
{
|
||||
$keys = [
|
||||
'kty' => 'The key parameter "kty" is missing.',
|
||||
'crv' => 'Curve parameter is missing',
|
||||
'x' => 'Point parameters are missing.',
|
||||
'y' => 'Point parameters are missing.',
|
||||
];
|
||||
foreach ($keys as $k => $v) {
|
||||
if (!array_key_exists($k, $jwk)) {
|
||||
throw new InvalidArgumentException($v);
|
||||
}
|
||||
}
|
||||
|
||||
if ('EC' !== $jwk['kty']) {
|
||||
throw new InvalidArgumentException('JWK is not an Elliptic Curve key.');
|
||||
}
|
||||
$this->values = $jwk;
|
||||
}
|
||||
}
|
272
wp-content/plugins/wp-webauthn/vendor/web-token/jwt-key-mgmt/KeyConverter/KeyConverter.php
vendored
Normal file
272
wp-content/plugins/wp-webauthn/vendor/web-token/jwt-key-mgmt/KeyConverter/KeyConverter.php
vendored
Normal file
@ -0,0 +1,272 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* Copyright (c) 2014-2020 Spomky-Labs
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Jose\Component\KeyManagement\KeyConverter;
|
||||
|
||||
use function array_key_exists;
|
||||
use Base64Url\Base64Url;
|
||||
use function count;
|
||||
use function extension_loaded;
|
||||
use InvalidArgumentException;
|
||||
use function is_array;
|
||||
use function is_string;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
class KeyConverter
|
||||
{
|
||||
/**
|
||||
* @throws InvalidArgumentException if the certificate file cannot be read
|
||||
*/
|
||||
public static function loadKeyFromCertificateFile(string $file): array
|
||||
{
|
||||
if (!file_exists($file)) {
|
||||
throw new InvalidArgumentException(sprintf('File "%s" does not exist.', $file));
|
||||
}
|
||||
$content = file_get_contents($file);
|
||||
if (!is_string($content)) {
|
||||
throw new InvalidArgumentException(sprintf('File "%s" cannot be read.', $file));
|
||||
}
|
||||
|
||||
return self::loadKeyFromCertificate($content);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws InvalidArgumentException if the OpenSSL extension is not available
|
||||
* @throws InvalidArgumentException if the certificate is invalid or cannot be loaded
|
||||
*/
|
||||
public static function loadKeyFromCertificate(string $certificate): array
|
||||
{
|
||||
if (!extension_loaded('openssl')) {
|
||||
throw new RuntimeException('Please install the OpenSSL extension');
|
||||
}
|
||||
|
||||
try {
|
||||
$res = openssl_x509_read($certificate);
|
||||
if (false === $res) {
|
||||
throw new InvalidArgumentException('Unable to load the certificate.');
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
$certificate = self::convertDerToPem($certificate);
|
||||
$res = openssl_x509_read($certificate);
|
||||
}
|
||||
if (false === $res) {
|
||||
throw new InvalidArgumentException('Unable to load the certificate.');
|
||||
}
|
||||
|
||||
return self::loadKeyFromX509Resource($res);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param resource $res
|
||||
*
|
||||
* @throws InvalidArgumentException if the OpenSSL extension is not available
|
||||
* @throws InvalidArgumentException if the certificate is invalid or cannot be loaded
|
||||
*/
|
||||
public static function loadKeyFromX509Resource($res): array
|
||||
{
|
||||
if (!extension_loaded('openssl')) {
|
||||
throw new RuntimeException('Please install the OpenSSL extension');
|
||||
}
|
||||
$key = openssl_get_publickey($res);
|
||||
if (false === $key) {
|
||||
throw new InvalidArgumentException('Unable to load the certificate.');
|
||||
}
|
||||
$details = openssl_pkey_get_details($key);
|
||||
if (!is_array($details)) {
|
||||
throw new InvalidArgumentException('Unable to load the certificate');
|
||||
}
|
||||
if (isset($details['key'])) {
|
||||
$values = self::loadKeyFromPEM($details['key']);
|
||||
openssl_x509_export($res, $out);
|
||||
$x5c = preg_replace('#-.*-#', '', $out);
|
||||
$x5c = preg_replace('~\R~', PHP_EOL, $x5c);
|
||||
if (!is_string($x5c)) {
|
||||
throw new InvalidArgumentException('Unable to load the certificate');
|
||||
}
|
||||
$x5c = trim($x5c);
|
||||
|
||||
$x5tsha1 = openssl_x509_fingerprint($res, 'sha1', true);
|
||||
$x5tsha256 = openssl_x509_fingerprint($res, 'sha256', true);
|
||||
if (!is_string($x5tsha1) || !is_string($x5tsha256)) {
|
||||
throw new InvalidArgumentException('Unable to compute the certificate fingerprint');
|
||||
}
|
||||
|
||||
$values['x5c'] = [$x5c];
|
||||
$values['x5t'] = Base64Url::encode($x5tsha1);
|
||||
$values['x5t#256'] = Base64Url::encode($x5tsha256);
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException('Unable to load the certificate');
|
||||
}
|
||||
|
||||
public static function loadFromKeyFile(string $file, ?string $password = null): array
|
||||
{
|
||||
$content = file_get_contents($file);
|
||||
if (!is_string($content)) {
|
||||
throw new InvalidArgumentException('Unable to load the key from the file.');
|
||||
}
|
||||
|
||||
return self::loadFromKey($content, $password);
|
||||
}
|
||||
|
||||
public static function loadFromKey(string $key, ?string $password = null): array
|
||||
{
|
||||
try {
|
||||
return self::loadKeyFromDER($key, $password);
|
||||
} catch (Throwable $e) {
|
||||
return self::loadKeyFromPEM($key, $password);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Be careful! The certificate chain is loaded, but it is NOT VERIFIED by any mean!
|
||||
* It is mandatory to verify the root CA or intermediate CA are trusted.
|
||||
* If not done, it may lead to potential security issues.
|
||||
*
|
||||
* @throws InvalidArgumentException if the certificate chain is empty
|
||||
* @throws InvalidArgumentException if the OpenSSL extension is not available
|
||||
*/
|
||||
public static function loadFromX5C(array $x5c): array
|
||||
{
|
||||
if (0 === count($x5c)) {
|
||||
throw new InvalidArgumentException('The certificate chain is empty');
|
||||
}
|
||||
foreach ($x5c as $id => $cert) {
|
||||
$x5c[$id] = '-----BEGIN CERTIFICATE-----'.PHP_EOL.chunk_split($cert, 64, PHP_EOL).'-----END CERTIFICATE-----';
|
||||
$x509 = openssl_x509_read($x5c[$id]);
|
||||
if (false === $x509) {
|
||||
throw new InvalidArgumentException('Unable to load the certificate chain');
|
||||
}
|
||||
$parsed = openssl_x509_parse($x509);
|
||||
if (false === $parsed) {
|
||||
throw new InvalidArgumentException('Unable to load the certificate chain');
|
||||
}
|
||||
}
|
||||
|
||||
return self::loadKeyFromCertificate(reset($x5c));
|
||||
}
|
||||
|
||||
private static function loadKeyFromDER(string $der, ?string $password = null): array
|
||||
{
|
||||
$pem = self::convertDerToPem($der);
|
||||
|
||||
return self::loadKeyFromPEM($pem, $password);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws InvalidArgumentException if the OpenSSL extension is not available
|
||||
* @throws InvalidArgumentException if the key cannot be loaded
|
||||
*/
|
||||
private static function loadKeyFromPEM(string $pem, ?string $password = null): array
|
||||
{
|
||||
if (1 === preg_match('#DEK-Info: (.+),(.+)#', $pem, $matches)) {
|
||||
$pem = self::decodePem($pem, $matches, $password);
|
||||
}
|
||||
|
||||
if (!extension_loaded('openssl')) {
|
||||
throw new RuntimeException('Please install the OpenSSL extension');
|
||||
}
|
||||
self::sanitizePEM($pem);
|
||||
$res = openssl_pkey_get_private($pem);
|
||||
if (false === $res) {
|
||||
$res = openssl_pkey_get_public($pem);
|
||||
}
|
||||
if (false === $res) {
|
||||
throw new InvalidArgumentException('Unable to load the key.');
|
||||
}
|
||||
|
||||
$details = openssl_pkey_get_details($res);
|
||||
if (!is_array($details) || !array_key_exists('type', $details)) {
|
||||
throw new InvalidArgumentException('Unable to get details of the key');
|
||||
}
|
||||
|
||||
switch ($details['type']) {
|
||||
case OPENSSL_KEYTYPE_EC:
|
||||
$ec_key = ECKey::createFromPEM($pem);
|
||||
|
||||
return $ec_key->toArray();
|
||||
|
||||
case OPENSSL_KEYTYPE_RSA:
|
||||
$rsa_key = RSAKey::createFromPEM($pem);
|
||||
|
||||
return $rsa_key->toArray();
|
||||
|
||||
default:
|
||||
throw new InvalidArgumentException('Unsupported key type');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method modifies the PEM to get 64 char lines and fix bug with old OpenSSL versions.
|
||||
*/
|
||||
private static function sanitizePEM(string &$pem): void
|
||||
{
|
||||
preg_match_all('#(-.*-)#', $pem, $matches, PREG_PATTERN_ORDER);
|
||||
$ciphertext = preg_replace('#-.*-|\r|\n| #', '', $pem);
|
||||
|
||||
$pem = $matches[0][0].PHP_EOL;
|
||||
$pem .= chunk_split($ciphertext, 64, PHP_EOL);
|
||||
$pem .= $matches[0][1].PHP_EOL;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string[] $matches
|
||||
*
|
||||
* @throws InvalidArgumentException if the password to decrypt the key is not provided
|
||||
* @throws InvalidArgumentException if the key cannot be loaded
|
||||
*/
|
||||
private static function decodePem(string $pem, array $matches, ?string $password = null): string
|
||||
{
|
||||
if (null === $password) {
|
||||
throw new InvalidArgumentException('Password required for encrypted keys.');
|
||||
}
|
||||
|
||||
$iv = pack('H*', trim($matches[2]));
|
||||
$iv_sub = mb_substr($iv, 0, 8, '8bit');
|
||||
$symkey = pack('H*', md5($password.$iv_sub));
|
||||
$symkey .= pack('H*', md5($symkey.$password.$iv_sub));
|
||||
$key = preg_replace('#^(?:Proc-Type|DEK-Info): .*#m', '', $pem);
|
||||
$ciphertext = base64_decode(preg_replace('#-.*-|\r|\n#', '', $key), true);
|
||||
if (!is_string($ciphertext)) {
|
||||
throw new InvalidArgumentException('Unable to encode the data.');
|
||||
}
|
||||
|
||||
$decoded = openssl_decrypt($ciphertext, mb_strtolower($matches[1]), $symkey, OPENSSL_RAW_DATA, $iv);
|
||||
if (false === $decoded) {
|
||||
throw new RuntimeException('Unable to decrypt the key');
|
||||
}
|
||||
$number = preg_match_all('#-{5}.*-{5}#', $pem, $result);
|
||||
if (2 !== $number) {
|
||||
throw new InvalidArgumentException('Unable to load the key');
|
||||
}
|
||||
|
||||
$pem = $result[0][0].PHP_EOL;
|
||||
$pem .= chunk_split(base64_encode($decoded), 64);
|
||||
$pem .= $result[0][1].PHP_EOL;
|
||||
|
||||
return $pem;
|
||||
}
|
||||
|
||||
private static function convertDerToPem(string $der_data): string
|
||||
{
|
||||
$pem = chunk_split(base64_encode($der_data), 64, PHP_EOL);
|
||||
|
||||
return '-----BEGIN CERTIFICATE-----'.PHP_EOL.$pem.'-----END CERTIFICATE-----'.PHP_EOL;
|
||||
}
|
||||
}
|
263
wp-content/plugins/wp-webauthn/vendor/web-token/jwt-key-mgmt/KeyConverter/RSAKey.php
vendored
Normal file
263
wp-content/plugins/wp-webauthn/vendor/web-token/jwt-key-mgmt/KeyConverter/RSAKey.php
vendored
Normal file
@ -0,0 +1,263 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* Copyright (c) 2014-2020 Spomky-Labs
|
||||
*
|
||||
* This software may be modified and distributed under the terms
|
||||
* of the MIT license. See the LICENSE file for details.
|
||||
*/
|
||||
|
||||
namespace Jose\Component\KeyManagement\KeyConverter;
|
||||
|
||||
use function array_key_exists;
|
||||
use Base64Url\Base64Url;
|
||||
use function extension_loaded;
|
||||
use function in_array;
|
||||
use InvalidArgumentException;
|
||||
use function is_array;
|
||||
use Jose\Component\Core\JWK;
|
||||
use Jose\Component\Core\Util\BigInteger;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
class RSAKey
|
||||
{
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $values = [];
|
||||
|
||||
/**
|
||||
* RSAKey constructor.
|
||||
*/
|
||||
private function __construct(array $data)
|
||||
{
|
||||
$this->loadJWK($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return RSAKey
|
||||
*/
|
||||
public static function createFromKeyDetails(array $details): self
|
||||
{
|
||||
$values = ['kty' => 'RSA'];
|
||||
$keys = [
|
||||
'n' => 'n',
|
||||
'e' => 'e',
|
||||
'd' => 'd',
|
||||
'p' => 'p',
|
||||
'q' => 'q',
|
||||
'dp' => 'dmp1',
|
||||
'dq' => 'dmq1',
|
||||
'qi' => 'iqmp',
|
||||
];
|
||||
foreach ($details as $key => $value) {
|
||||
if (in_array($key, $keys, true)) {
|
||||
$value = Base64Url::encode($value);
|
||||
$values[array_search($key, $keys, true)] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return new self($values);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws RuntimeException if the extension OpenSSL is not available
|
||||
* @throws InvalidArgumentException if the key cannot be loaded
|
||||
*
|
||||
* @return RSAKey
|
||||
*/
|
||||
public static function createFromPEM(string $pem): self
|
||||
{
|
||||
if (!extension_loaded('openssl')) {
|
||||
throw new RuntimeException('Please install the OpenSSL extension');
|
||||
}
|
||||
$res = openssl_pkey_get_private($pem);
|
||||
if (false === $res) {
|
||||
$res = openssl_pkey_get_public($pem);
|
||||
}
|
||||
if (false === $res) {
|
||||
throw new InvalidArgumentException('Unable to load the key.');
|
||||
}
|
||||
|
||||
$details = openssl_pkey_get_details($res);
|
||||
if (!is_array($details) || !isset($details['rsa'])) {
|
||||
throw new InvalidArgumentException('Unable to load the key.');
|
||||
}
|
||||
|
||||
return self::createFromKeyDetails($details['rsa']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return RSAKey
|
||||
*/
|
||||
public static function createFromJWK(JWK $jwk): self
|
||||
{
|
||||
return new self($jwk->all());
|
||||
}
|
||||
|
||||
public function isPublic(): bool
|
||||
{
|
||||
return !array_key_exists('d', $this->values);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param RSAKey $private
|
||||
*
|
||||
* @return RSAKey
|
||||
*/
|
||||
public static function toPublic(self $private): self
|
||||
{
|
||||
$data = $private->toArray();
|
||||
$keys = ['p', 'd', 'q', 'dp', 'dq', 'qi'];
|
||||
foreach ($keys as $key) {
|
||||
if (array_key_exists($key, $data)) {
|
||||
unset($data[$key]);
|
||||
}
|
||||
}
|
||||
|
||||
return new self($data);
|
||||
}
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return $this->values;
|
||||
}
|
||||
|
||||
public function toJwk(): JWK
|
||||
{
|
||||
return new JWK($this->values);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method will try to add Chinese Remainder Theorem (CRT) parameters.
|
||||
* With those primes, the decryption process is really fast.
|
||||
*/
|
||||
public function optimize(): void
|
||||
{
|
||||
if (array_key_exists('d', $this->values)) {
|
||||
$this->populateCRT();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws InvalidArgumentException if the key is invalid or not an RSA key
|
||||
*/
|
||||
private function loadJWK(array $jwk): void
|
||||
{
|
||||
if (!array_key_exists('kty', $jwk)) {
|
||||
throw new InvalidArgumentException('The key parameter "kty" is missing.');
|
||||
}
|
||||
if ('RSA' !== $jwk['kty']) {
|
||||
throw new InvalidArgumentException('The JWK is not a RSA key.');
|
||||
}
|
||||
|
||||
$this->values = $jwk;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method adds Chinese Remainder Theorem (CRT) parameters if primes 'p' and 'q' are available.
|
||||
* If 'p' and 'q' are missing, they are computed and added to the key data.
|
||||
*/
|
||||
private function populateCRT(): void
|
||||
{
|
||||
if (!array_key_exists('p', $this->values) && !array_key_exists('q', $this->values)) {
|
||||
$d = BigInteger::createFromBinaryString(Base64Url::decode($this->values['d']));
|
||||
$e = BigInteger::createFromBinaryString(Base64Url::decode($this->values['e']));
|
||||
$n = BigInteger::createFromBinaryString(Base64Url::decode($this->values['n']));
|
||||
|
||||
[$p, $q] = $this->findPrimeFactors($d, $e, $n);
|
||||
$this->values['p'] = Base64Url::encode($p->toBytes());
|
||||
$this->values['q'] = Base64Url::encode($q->toBytes());
|
||||
}
|
||||
|
||||
if (array_key_exists('dp', $this->values) && array_key_exists('dq', $this->values) && array_key_exists('qi', $this->values)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$one = BigInteger::createFromDecimal(1);
|
||||
$d = BigInteger::createFromBinaryString(Base64Url::decode($this->values['d']));
|
||||
$p = BigInteger::createFromBinaryString(Base64Url::decode($this->values['p']));
|
||||
$q = BigInteger::createFromBinaryString(Base64Url::decode($this->values['q']));
|
||||
|
||||
$this->values['dp'] = Base64Url::encode($d->mod($p->subtract($one))->toBytes());
|
||||
$this->values['dq'] = Base64Url::encode($d->mod($q->subtract($one))->toBytes());
|
||||
$this->values['qi'] = Base64Url::encode($q->modInverse($p)->toBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws RuntimeException if the prime factors cannot be found
|
||||
*
|
||||
* @return BigInteger[]
|
||||
*/
|
||||
private function findPrimeFactors(BigInteger $d, BigInteger $e, BigInteger $n): array
|
||||
{
|
||||
$zero = BigInteger::createFromDecimal(0);
|
||||
$one = BigInteger::createFromDecimal(1);
|
||||
$two = BigInteger::createFromDecimal(2);
|
||||
|
||||
$k = $d->multiply($e)->subtract($one);
|
||||
|
||||
if ($k->isEven()) {
|
||||
$r = $k;
|
||||
$t = $zero;
|
||||
|
||||
do {
|
||||
$r = $r->divide($two);
|
||||
$t = $t->add($one);
|
||||
} while ($r->isEven());
|
||||
|
||||
$found = false;
|
||||
$y = null;
|
||||
|
||||
for ($i = 1; $i <= 100; ++$i) {
|
||||
$g = BigInteger::random($n->subtract($one));
|
||||
$y = $g->modPow($r, $n);
|
||||
|
||||
if ($y->equals($one) || $y->equals($n->subtract($one))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for ($j = $one; $j->lowerThan($t->subtract($one)); $j = $j->add($one)) {
|
||||
$x = $y->modPow($two, $n);
|
||||
|
||||
if ($x->equals($one)) {
|
||||
$found = true;
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
if ($x->equals($n->subtract($one))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$y = $x;
|
||||
}
|
||||
|
||||
$x = $y->modPow($two, $n);
|
||||
if ($x->equals($one)) {
|
||||
$found = true;
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (null === $y) {
|
||||
throw new InvalidArgumentException('Unable to find prime factors.');
|
||||
}
|
||||
if (true === $found) {
|
||||
$p = $y->subtract($one)->gcd($n);
|
||||
$q = $n->divide($p);
|
||||
|
||||
return [$p, $q];
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException('Unable to find prime factors.');
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user