Ejemplo n.º 1
0
 /**
  *
  */
 public function testValidCEK()
 {
     $header = [];
     $key = new JWK(['kty' => 'dir', 'dir' => Base64Url::encode('ABCD')]);
     $dir = new Dir();
     $this->assertEquals('ABCD', $dir->getCEK($key, $header));
 }
Ejemplo n.º 2
0
 /**
  * @param $data
  *
  * @throws \Exception
  * @throws \FG\ASN1\Exception\ParserException
  *
  * @return array
  */
 private function loadPEM($data)
 {
     $res = openssl_pkey_get_private($data);
     if (false === $res) {
         $res = openssl_pkey_get_public($data);
     }
     if (false === $res) {
         throw new \Exception('Unable to load the key');
     }
     $details = openssl_pkey_get_details($res);
     if (!array_key_exists('rsa', $details)) {
         throw new \Exception('Unable to load the key');
     }
     foreach ($details['rsa'] as $key => $value) {
         $value = Base64Url::encode($value);
         if ($key === 'dmp1') {
             $this->dp = $value;
         } elseif ($key === 'dmq1') {
             $this->dq = $value;
         } elseif ($key === 'iqmp') {
             $this->qi = $value;
         } else {
             $this->{$key} = $value;
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function calculateSessionState(ServerRequestInterface $request, AuthorizationInterface $authorization, $browser_state)
 {
     $origin = $this->getOriginUri($authorization->getRedirectUri());
     $salt = Base64Url::encode(random_bytes(16));
     $hash = hash('sha256', sprintf('%s%s%s%s', $authorization->getClient()->getPublicId(), $origin, $browser_state, $salt));
     return sprintf('%s.%s', $hash, $salt);
 }
Ejemplo n.º 4
0
 public function thumbprint($hash_algorithm)
 {
     Assertion::inArray($hash_algorithm, hash_algos(), sprintf('Hash algorithm "%s" is not supported', $hash_algorithm));
     $values = array_intersect_key($this->getAll(), array_flip(['kty', 'n', 'e', 'crv', 'x', 'y', 'k']));
     ksort($values);
     $input = json_encode($values);
     return Base64Url::encode(hash($hash_algorithm, $input, true));
 }
Ejemplo n.º 5
0
 /**
  *
  */
 public function testRS512Sign()
 {
     $rsa = new RS512();
     $key = new JWK(['kty' => 'RSA', 'n' => 'tpS1ZmfVKVP5KofIhMBP0tSWc4qlh6fm2lrZSkuKxUjEaWjzZSzs72gEIGxraWusMdoRuV54xsWRyf5KeZT0S-I5Prle3Idi3gICiO4NwvMk6JwSBcJWwmSLFEKyUSnB2CtfiGc0_5rQCpcEt_Dn5iM-BNn7fqpoLIbks8rXKUIj8-qMVqkTXsEKeKinE23t1ykMldsNaaOH-hvGti5Jt2DMnH1JjoXdDXfxvSP_0gjUYb0ektudYFXoA6wekmQyJeImvgx4Myz1I4iHtkY_Cp7J4Mn1ejZ6HNmyvoTE_4OuY1uCeYv4UyXFc1s1uUyYtj4z57qsHGsS4dQ3A2MJsw', 'e' => 'AQAB', 'p' => '5BGU1c7af_5sFyfsa-onIJgo5BZu8uHvz3Uyb8OA0a-G9UPO1ShLYjX0wUfhZcFB7fwPtgmmYAN6wKGVce9eMAbX4PliPk3r-BcpZuPKkuLk_wFvgWAQ5Hqw2iEuwXLV0_e8c2gaUt_hyMC5-nFc4v0Bmv6NT6Pfry-UrK3BKWc', 'd' => 'Kp0KuZwCZGL1BLgsVM-N0edMNitl9wN5Hf2WOYDoIqOZNAEKzdJuenIMhITJjRFUX05GVL138uyp2js_pqDdY9ipA7rAKThwGuDdNphZHech9ih3DGEPXs-YpmHqvIbCd3GoGm38MKwxYkddEpFnjo8rKna1_BpJthrFxjDRhw9DxJBycOdH2yWTyp62ZENPvneK40H2a57W4QScTgfecZqD59m2fGUaWaX5uUmIxaEmtGoJnd9RE4oywKhgN7_TK7wXRlqA4UoRPiH2ACrdU-_cLQL9Jc0u0GqZJK31LDbOeN95QgtSCc72k3Vtzy3CrVpp5TAA67s1Gj9Skn-CAQ', 'q' => 'zPD-B-nrngwF-O99BHvb47XGKR7ON8JCI6JxavzIkusMXCB8rMyYW8zLs68L8JLAzWZ34oMq0FPUnysBxc5nTF8Nb4BZxTZ5-9cHfoKrYTI3YWsmVW2FpCJFEjMs4NXZ28PBkS9b4zjfS2KhNdkmCeOYU0tJpNfwmOTI90qeUdU', 'dp' => 'aJrzw_kjWK9uDlTeaES2e4muv6bWbopYfrPHVWG7NPGoGdhnBnd70-jhgMEiTZSNU8VXw2u7prAR3kZ-kAp1DdwlqedYOzFsOJcPA0UZhbORyrBy30kbll_7u6CanFm6X4VyJxCpejd7jKNw6cCTFP1sfhWg5NVJ5EUTkPwE66M', 'dq' => 'Swz1-m_vmTFN_pu1bK7vF7S5nNVrL4A0OFiEsGliCmuJWzOKdL14DiYxctvnw3H6qT2dKZZfV2tbse5N9-JecdldUjfuqAoLIe7dD7dKi42YOlTC9QXmqvTh1ohnJu8pmRFXEZQGUm_BVhoIb2_WPkjav6YSkguCUHt4HRd2YwE', 'qi' => 'BocuCOEOq-oyLDALwzMXU8gOf3IL1Q1_BWwsdoANoh6i179psxgE4JXToWcpXZQQqub8ngwE6uR9fpd3m6N_PL4T55vbDDyjPKmrL2ttC2gOtx9KrpPh-Z7LQRo4BE48nHJJrystKHfFlaH2G7JxHNgMBYVADyttN09qEoav8Os']);
     $data = 'Je suis Charlie';
     $signature = $rsa->sign($key, $data);
     $this->assertEquals('dCFJjJdXUz_0zaOveSvb0aJulgjLwH4cf2d3d_BRfCpUKUjPT9KXiJiBl9JBVaGhLzbHmDmiLu1ZIsC8sAtW1Z0Mt6p4TpNxbGlAG37UtaN8Y5x7RiRpE_4DWNqcUsZJbsQt7eOs0vDl70TXGQzTT465HNmVW-DHw8cZLsxhu2Qia7i0UOhNO0fZScf0t843s0DLQ8hSCN5bbO-Zv33Tv3rx1EuNRSypIQDHWlN6qtX4-K6XO_bNo2-Tole9eTwOkuuQibTh_9Xa7jXP_SI6Qj6nqJZxaZmTO4NdBbNx1kwtYec8jBYqkv1H7E7wfN8EpOdhL1lC2DSq6tR2vP8eIQ', Base64Url::encode($signature));
     $this->assertTrue($rsa->verify($key, $data, $signature));
 }
Ejemplo n.º 6
0
 public function thumbprint($hash_algorithm)
 {
     if (false === in_array($hash_algorithm, hash_algos())) {
         throw new \InvalidArgumentException(sprintf('Hash algorithm "%s" is not supported', $hash_algorithm));
     }
     $values = array_intersect_key($this->getAll(), array_flip(['kty', 'n', 'e', 'crv', 'x', 'y', 'k']));
     ksort($values);
     $input = json_encode($values);
     return Base64Url::encode(hash($hash_algorithm, $input, true));
 }
Ejemplo n.º 7
0
 /**
  *
  */
 public function testA256KW()
 {
     $header = [];
     $key = new JWK(['kty' => 'oct', 'k' => Base64Url::encode(hex2bin('000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F'))]);
     $cek = hex2bin('00112233445566778899AABBCCDDEEFF000102030405060708090A0B0C0D0E0F');
     $aeskw = new A256KW();
     $wrapped_cek = $aeskw->encryptKey($key, $cek, $header);
     $this->assertEquals($wrapped_cek, hex2bin('28C9F404C4B810F4CBCCB35CFB87F8263F5786E2D80ED326CBC7F0E71A99F43BFB988B9B7A02DD21'));
     $this->assertEquals($cek, $aeskw->decryptKey($key, $wrapped_cek, $header));
 }
Ejemplo n.º 8
0
 /**
  * {@inheritdoc}
  */
 public function wrapKey(JWKInterface $key, $cek, array $complete_headers, array &$additional_headers)
 {
     $this->checkKey($key);
     $kek = Base64Url::decode($key->get('k'));
     $iv = random_bytes(96 / 8);
     $additional_headers['iv'] = Base64Url::encode($iv);
     list($encrypted_cek, $tag) = AESGCM::encrypt($kek, $iv, $cek, null);
     $additional_headers['tag'] = Base64Url::encode($tag);
     return $encrypted_cek;
 }
Ejemplo n.º 9
0
 /**
  * @param \Jose\Object\JWKInterface $key
  * @param string                    $cek
  * @param array                     $header
  *
  * @return mixed
  */
 public function encryptKey(JWKInterface $key, $cek, array &$header)
 {
     $this->checkKey($key);
     $cipher = Cipher::aes(Cipher::MODE_GCM, $this->getKeySize());
     $cipher->setAAD(null);
     $iv = openssl_random_pseudo_bytes(96 / 8);
     $encryted_cek = $cipher->encrypt($cek, Base64Url::decode($key->get('k')), $iv);
     $header['iv'] = Base64Url::encode($iv);
     $header['tag'] = Base64Url::encode($cipher->getTag());
     return $encryted_cek;
 }
 /**
  *
  */
 public function testPBES2HS512A256KW()
 {
     $header = ['alg' => 'PBES2-HS512+A256KW', 'enc' => 'A256CBC-HS512', 'cty' => 'jwk+json'];
     $key = new JWK(['kty' => 'oct', 'k' => Base64Url::encode($this->convertArrayToBinString([84, 104, 117, 115, 32, 102, 114, 111, 109, 32, 109, 121, 32, 108, 105, 112, 115, 44, 32, 98, 121, 32, 121, 111, 117, 114, 115, 44, 32, 109, 121, 32, 115, 105, 110, 32, 105, 115, 32, 112, 117, 114, 103, 101, 100, 46]))]);
     $cek = $this->convertArrayToBinString([111, 27, 25, 52, 66, 29, 20, 78, 92, 176, 56, 240, 65, 208, 82, 112, 161, 131, 36, 55, 202, 236, 185, 172, 129, 23, 153, 194, 195, 48, 253, 182]);
     $pbes2 = new PBES2HS512A256KW();
     $encrypted_cek = $pbes2->encryptKey($key, $cek, $header);
     $this->assertTrue(isset($header['p2s']));
     $this->assertEquals(4096, $header['p2c']);
     $this->assertEquals($cek, $pbes2->decryptKey($key, $encrypted_cek, $header));
 }
Ejemplo n.º 11
0
 /**
  * @param \Jose\Object\JWSInterface       $jws
  * @param \Jose\Object\SignatureInterface $signature
  *
  * @return string
  */
 private function getInputToSign(Object\JWSInterface $jws, Object\SignatureInterface $signature)
 {
     $this->checkB64HeaderAndCrit($signature);
     $encoded_protected_headers = $signature->getEncodedProtectedHeaders();
     $payload = $jws->getPayload();
     if (!$signature->hasProtectedHeader('b64') || true === $signature->getProtectedHeader('b64')) {
         $encoded_payload = Base64Url::encode(is_string($payload) ? $payload : json_encode($payload));
         return sprintf('%s.%s', $encoded_protected_headers, $encoded_payload);
     }
     return sprintf('%s.%s', $encoded_protected_headers, $payload);
 }
 /**
  * @see https://tools.ietf.org/html/rfc7516#appendix-A.1
  */
 public function testA256GCMDecryptTestVector()
 {
     $algorithm = new A256GCM();
     $header = Base64Url::encode(json_encode(['alg' => 'RSA-OAEP', 'enc' => 'A256GCM']));
     $cek = $this->convertArrayToBinString([177, 161, 244, 128, 84, 143, 225, 115, 63, 180, 3, 255, 107, 154, 212, 246, 138, 7, 110, 91, 112, 46, 34, 105, 47, 130, 203, 46, 122, 234, 64, 252]);
     $iv = $this->convertArrayToBinString([227, 197, 117, 252, 2, 219, 233, 68, 180, 225, 77, 219]);
     $tag = $this->convertArrayToBinString([92, 80, 104, 49, 133, 25, 161, 215, 173, 101, 219, 211, 136, 91, 210, 145]);
     $cyphertext = $this->convertArrayToBinString([229, 236, 166, 241, 53, 191, 115, 196, 174, 43, 73, 109, 39, 122, 233, 96, 140, 206, 120, 52, 51, 237, 48, 11, 190, 219, 186, 80, 111, 104, 50, 142, 47, 167, 59, 61, 181, 127, 196, 21, 40, 82, 242, 32, 123, 143, 168, 226, 73, 216, 176, 144, 138, 247, 106, 60, 16, 205, 160, 109, 64, 63, 192]);
     $expected_plaintext = 'The true sign of intelligence is not knowledge but imagination.';
     $this->assertEquals('eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZHQ00ifQ', $header);
     $this->assertEquals($expected_plaintext, $algorithm->decryptContent($cyphertext, $cek, $iv, null, $header, $tag));
 }
Ejemplo n.º 13
0
 /**
  *
  */
 public function testA256GCMKW()
 {
     $header = [];
     $key = new JWK(['kty' => 'oct', 'k' => Base64Url::encode(hex2bin('000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F'))]);
     $cek = hex2bin('00112233445566778899AABBCCDDEEFF000102030405060708090A0B0C0D0E0F');
     $aeskw = new A256GCMKW();
     $wrapped_cek = $aeskw->encryptKey($key, $cek, $header);
     $this->assertTrue(array_key_exists('iv', $header));
     $this->assertTrue(array_key_exists('tag', $header));
     $this->assertNotNull($header['iv']);
     $this->assertNotNull($header['tag']);
     $this->assertEquals($cek, $aeskw->decryptKey($key, $wrapped_cek, $header));
 }
Ejemplo n.º 14
0
 function setVAPIDInfo($privateKey, $audience, $subject)
 {
     if (!USE_VAPID || !$privateKey || !$audience || !$subject) {
         return;
     }
     $builder = new Builder();
     $token = $builder->setAudience($audience)->setExpiration(time() + 86400)->setSubject($subject)->sign(new Sha256(), new Key($privateKey))->getToken();
     $this->additionalHeaders['Authorization'] = 'Bearer ' . $token;
     $privKeySerializer = new PemPrivateKeySerializer(new DerPrivateKeySerializer());
     $privateKeyObject = $privKeySerializer->parse($privateKey);
     $publicKeyObject = $privateKeyObject->getPublicKey();
     $pointSerializer = new UncompressedPointSerializer(EccFactory::getAdapter());
     $this->additionalHeaders['Crypto-Key'] = 'p256ecdsa=' . Base64Url::encode(hex2bin($pointSerializer->serialize($publicKeyObject->getPoint())));
 }
Ejemplo n.º 15
0
 /**
  * {@inheritdoc}
  */
 public function wrapKey(JWKInterface $key, $cek, array $complete_headers, array &$additional_headers)
 {
     $this->checkKey($key);
     $this->checkHeaderAlgorithm($complete_headers);
     $wrapper = $this->getWrapper();
     $hash_algorithm = $this->getHashAlgorithm();
     $key_size = $this->getKeySize();
     $salt = random_bytes($this->salt_size);
     $password = Base64Url::decode($key->get('k'));
     // We set headers parameters
     $additional_headers['p2s'] = Base64Url::encode($salt);
     $additional_headers['p2c'] = $this->nb_count;
     $derived_key = hash_pbkdf2($hash_algorithm, $password, $complete_headers['alg'] . "" . $salt, $this->nb_count, $key_size, true);
     return $wrapper->wrap($derived_key, $cek);
 }
Ejemplo n.º 16
0
 /**
  * @param JWKInterface $key
  * @param string       $cek
  * @param array        $header
  *
  * @return mixed
  */
 public function encryptKey(JWKInterface $key, $cek, array &$header)
 {
     $this->checkKey($key);
     $this->checkHeaderAlgorithm($header);
     $wrapper = $this->getWrapper();
     $hash_algorithm = $this->getHashAlgorithm();
     $key_size = $this->getKeySize();
     $salt = openssl_random_pseudo_bytes($key_size / 8);
     $count = 4096;
     $password = Base64Url::decode($key->getValue('k'));
     // We set headers parameters
     $header['p2s'] = Base64Url::encode($salt);
     $header['p2c'] = $count;
     $derived_key = PBKDF2::deriveKey($hash_algorithm, $password, $header['alg'] . "" . $salt, $count, $key_size, true);
     return $wrapper->wrap($derived_key, $cek);
 }
Ejemplo n.º 17
0
 function get_public_key($privateKey)
 {
     $publicKeyVal = __('Your private key is invalid.', 'web-push');
     error_reporting(E_ERROR);
     try {
         $privKeySerializer = new PemPrivateKeySerializer(new DerPrivateKeySerializer());
         $privateKeyObject = $privKeySerializer->parse($privateKey);
         $publicKeyObject = $privateKeyObject->getPublicKey();
         $pointSerializer = new UncompressedPointSerializer(EccFactory::getAdapter());
         $publicKeyVal = Base64Url::encode(hex2bin($pointSerializer->serialize($publicKeyObject->getPoint())));
     } catch (Exception $e) {
         // Ignore exceptions while getting the public key from the private key.
     }
     error_reporting(E_ALL);
     return $publicKeyVal;
 }
Ejemplo n.º 18
0
 /**
  * @param array $header
  *
  * @return \Jose\JWKInterface|null
  */
 protected function findByKid(array $header)
 {
     if (!isset($header['kid'])) {
         return;
     }
     switch ($header['kid']) {
         case '2010-12-29':
             return $this->createJWK(['kty' => 'RSA', 'n' => 'ofgWCuLjybRlzo0tZWJjNiuSfb4p4fAkd_wWJcyQoTbji9k0l8W26mPddxHmfHQp-Vaw-4qPCJrcS2mJPMEzP1Pt0Bm4d4QlL-yRT-SFd2lZS-pCgNMsD1W_YpRPEwOWvG6b32690r2jZ47soMZo9wGzjb_7OMg0LOL-bSf63kpaSHSXndS5z5rexMdbBYUsLA9e-KXBdQOS-UTo7WTBEMa2R2CapHg665xsmtdVMTBQY4uDZlxvb3qCo5ZwKh9kG4LT6_I5IhlJH7aGhyxXFvUK-DWNmoudF8NAco9_h9iaGNj8q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXpoQ', 'e' => 'AQAB', 'd' => 'Eq5xpGnNCivDflJsRQBXHx1hdR1k6Ulwe2JZD50LpXyWPEAeP88vLNO97IjlA7_GQ5sLKMgvfTeXZx9SE-7YwVol2NXOoAJe46sui395IW_GO-pWJ1O0BkTGoVEn2bKVRUCgu-GjBVaYLU6f3l9kJfFNS3E0QbVdxzubSu3Mkqzjkn439X0M_V51gfpRLI9JYanrC4D4qAdGcopV_0ZHHzQlBjudU2QvXt4ehNYTCBr6XCLQUShb1juUO1ZdiYoFaFQT5Tw8bGUl_x_jTj3ccPDVZFD9pIuhLhBOneufuBiB4cS98l2SR_RQyGWSeWjnczT0QU91p1DhOVRuOopznQ']);
         case 'e9bc097a-ce51-4036-9562-d2ade882db0d':
             return $this->createJWK(['kty' => 'EC', 'crv' => 'P-256', 'x' => 'f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU', 'y' => 'x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0', 'd' => 'jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI']);
         case '123456789':
             return $this->createJWK(['kty' => 'RSA', 'n' => 'tpS1ZmfVKVP5KofIhMBP0tSWc4qlh6fm2lrZSkuKxUjEaWjzZSzs72gEIGxraWusMdoRuV54xsWRyf5KeZT0S-I5Prle3Idi3gICiO4NwvMk6JwSBcJWwmSLFEKyUSnB2CtfiGc0_5rQCpcEt_Dn5iM-BNn7fqpoLIbks8rXKUIj8-qMVqkTXsEKeKinE23t1ykMldsNaaOH-hvGti5Jt2DMnH1JjoXdDXfxvSP_0gjUYb0ektudYFXoA6wekmQyJeImvgx4Myz1I4iHtkY_Cp7J4Mn1ejZ6HNmyvoTE_4OuY1uCeYv4UyXFc1s1uUyYtj4z57qsHGsS4dQ3A2MJsw', 'e' => 'AQAB', 'p' => '5BGU1c7af_5sFyfsa-onIJgo5BZu8uHvz3Uyb8OA0a-G9UPO1ShLYjX0wUfhZcFB7fwPtgmmYAN6wKGVce9eMAbX4PliPk3r-BcpZuPKkuLk_wFvgWAQ5Hqw2iEuwXLV0_e8c2gaUt_hyMC5-nFc4v0Bmv6NT6Pfry-UrK3BKWc', 'd' => 'Kp0KuZwCZGL1BLgsVM-N0edMNitl9wN5Hf2WOYDoIqOZNAEKzdJuenIMhITJjRFUX05GVL138uyp2js_pqDdY9ipA7rAKThwGuDdNphZHech9ih3DGEPXs-YpmHqvIbCd3GoGm38MKwxYkddEpFnjo8rKna1_BpJthrFxjDRhw9DxJBycOdH2yWTyp62ZENPvneK40H2a57W4QScTgfecZqD59m2fGUaWaX5uUmIxaEmtGoJnd9RE4oywKhgN7_TK7wXRlqA4UoRPiH2ACrdU-_cLQL9Jc0u0GqZJK31LDbOeN95QgtSCc72k3Vtzy3CrVpp5TAA67s1Gj9Skn-CAQ', 'q' => 'zPD-B-nrngwF-O99BHvb47XGKR7ON8JCI6JxavzIkusMXCB8rMyYW8zLs68L8JLAzWZ34oMq0FPUnysBxc5nTF8Nb4BZxTZ5-9cHfoKrYTI3YWsmVW2FpCJFEjMs4NXZ28PBkS9b4zjfS2KhNdkmCeOYU0tJpNfwmOTI90qeUdU', 'dp' => 'aJrzw_kjWK9uDlTeaES2e4muv6bWbopYfrPHVWG7NPGoGdhnBnd70-jhgMEiTZSNU8VXw2u7prAR3kZ-kAp1DdwlqedYOzFsOJcPA0UZhbORyrBy30kbll_7u6CanFm6X4VyJxCpejd7jKNw6cCTFP1sfhWg5NVJ5EUTkPwE66M', 'dq' => 'Swz1-m_vmTFN_pu1bK7vF7S5nNVrL4A0OFiEsGliCmuJWzOKdL14DiYxctvnw3H6qT2dKZZfV2tbse5N9-JecdldUjfuqAoLIe7dD7dKi42YOlTC9QXmqvTh1ohnJu8pmRFXEZQGUm_BVhoIb2_WPkjav6YSkguCUHt4HRd2YwE', 'qi' => 'BocuCOEOq-oyLDALwzMXU8gOf3IL1Q1_BWwsdoANoh6i179psxgE4JXToWcpXZQQqub8ngwE6uR9fpd3m6N_PL4T55vbDDyjPKmrL2ttC2gOtx9KrpPh-Z7LQRo4BE48nHJJrystKHfFlaH2G7JxHNgMBYVADyttN09qEoav8Os']);
         case '71ee230371d19630bc17fb90ccf20ae632ad8cf8':
             return $this->createJWK(['kty' => 'RSA', 'alg' => 'RS256', 'use' => 'sig', 'kid' => '71ee230371d19630bc17fb90ccf20ae632ad8cf8', 'n' => 'vnMTRCMvsS04M1yaKR112aB8RxOkWHFixZO68wCRlVLxK4ugckXVD_Ebcq-kms1T2XpoWntVfBuX40r2GvcD9UsTFt_MZlgd1xyGwGV6U_tfQUll5mKxCPjr60h83LXKJ_zmLXIqkV8tAoIg78a5VRWoms_0Bn09DKT3-RBWFjk=', 'e' => 'AQAB']);
         case '02491f945c951adf156f370788e8ccdabf8877a8':
             return $this->createJWK(['kty' => 'RSA', 'alg' => 'RS256', 'use' => 'sig', 'kid' => '02491f945c951adf156f370788e8ccdabf8877a8', 'n' => 'rI67uHIDWDgCy_Ut-FhhjTCkEcqzoO80IRgdpk_fJHlDmXhMTJKPizxbIEMs0wRHRZpwH-4D20thpnQB5Mgx6-XM9kOvcYpHSdcYME77BwX6uQG-hw2w77NOhYiCSZCLzx-5ld5Wjy0dympL-ExqQw-wrWipMX7NQhIbJqVbZ18=', 'e' => 'AQAB']);
         case 'DIR_1':
             return $this->createJWK(['kid' => 'DIR_1', 'kty' => 'dir', 'dir' => Base64Url::encode(hex2bin('00112233445566778899AABBCCDDEEFF000102030405060708090A0B0C0D0E0F'))]);
     }
 }
Ejemplo n.º 19
0
 /**
  * @param resource $res
  *
  * @throws \Exception
  *
  * @return array
  */
 public static function loadKeyFromX509Resource($res)
 {
     $key = openssl_get_publickey($res);
     $details = openssl_pkey_get_details($key);
     if (isset($details['key'])) {
         $values = self::loadKeyFromPEM($details['key']);
         openssl_x509_export($res, $out);
         $values['x5c'] = [trim(preg_replace('#-.*-#', '', $out))];
         if (function_exists('openssl_x509_fingerprint')) {
             $values['x5t'] = Base64Url::encode(openssl_x509_fingerprint($res, 'sha1', true));
             $values['x5t#256'] = Base64Url::encode(openssl_x509_fingerprint($res, 'sha256', true));
         } else {
             openssl_x509_export($res, $pem);
             $values['x5t'] = Base64Url::encode(self::calculateX509Fingerprint($pem, 'sha1', true));
             $values['x5t#256'] = Base64Url::encode(self::calculateX509Fingerprint($pem, 'sha256', true));
         }
         return $values;
     }
     throw new \InvalidArgumentException('Unable to load the certificate');
 }
Ejemplo n.º 20
0
 /**
  * @param string $payload          With padding
  * @param string $userPublicKey    Base 64 encoded (MIME or URL-safe)
  * @param string $userAuthToken    Base 64 encoded (MIME or URL-safe)
  * @param bool   $nativeEncryption Use OpenSSL (>PHP7.1)
  *
  * @return array
  */
 public static function encrypt($payload, $userPublicKey, $userAuthToken, $nativeEncryption)
 {
     $userPublicKey = Base64Url::decode($userPublicKey);
     $userAuthToken = Base64Url::decode($userAuthToken);
     // initialize utilities
     $math = EccFactory::getAdapter();
     $pointSerializer = new UncompressedPointSerializer($math);
     $generator = EccFactory::getNistCurves()->generator256();
     $curve = EccFactory::getNistCurves()->curve256();
     // get local key pair
     $localPrivateKeyObject = $generator->createPrivateKey();
     $localPublicKeyObject = $localPrivateKeyObject->getPublicKey();
     $localPublicKey = hex2bin($pointSerializer->serialize($localPublicKeyObject->getPoint()));
     // get user public key object
     $pointUserPublicKey = $pointSerializer->unserialize($curve, bin2hex($userPublicKey));
     $userPublicKeyObject = $generator->getPublicKeyFrom($pointUserPublicKey->getX(), $pointUserPublicKey->getY(), $generator->getOrder());
     // get shared secret from user public key and local private key
     $sharedSecret = hex2bin($math->decHex(gmp_strval($userPublicKeyObject->getPoint()->mul($localPrivateKeyObject->getSecret())->getX())));
     // generate salt
     $salt = openssl_random_pseudo_bytes(16);
     // section 4.3
     $ikm = !empty($userAuthToken) ? self::hkdf($userAuthToken, $sharedSecret, 'Content-Encoding: auth' . chr(0), 32) : $sharedSecret;
     // section 4.2
     $context = self::createContext($userPublicKey, $localPublicKey);
     // derive the Content Encryption Key
     $contentEncryptionKeyInfo = self::createInfo('aesgcm', $context);
     $contentEncryptionKey = self::hkdf($salt, $ikm, $contentEncryptionKeyInfo, 16);
     // section 3.3, derive the nonce
     $nonceInfo = self::createInfo('nonce', $context);
     $nonce = self::hkdf($salt, $ikm, $nonceInfo, 12);
     // encrypt
     // "The additional data passed to each invocation of AEAD_AES_128_GCM is a zero-length octet sequence."
     if (!$nativeEncryption) {
         list($encryptedText, $tag) = \AESGCM\AESGCM::encrypt($contentEncryptionKey, $nonce, $payload, '');
     } else {
         $encryptedText = openssl_encrypt($payload, 'aes-128-gcm', $contentEncryptionKey, OPENSSL_RAW_DATA, $nonce, $tag);
         // base 64 encoded
     }
     // return values in url safe base64
     return array('localPublicKey' => Base64Url::encode($localPublicKey), 'salt' => Base64Url::encode($salt), 'cipherText' => $encryptedText . $tag);
 }
Ejemplo n.º 21
0
 /**
  * @param \Jose\Object\SignatureInstructionInterface $instruction
  * @param string                                     $jwt_payload
  * @param array                                      $additional_header
  *
  * @return array
  */
 protected function computeSignature(SignatureInstructionInterface $instruction, $jwt_payload, array $additional_header)
 {
     $protected_header = array_merge($instruction->getProtectedHeader(), $additional_header);
     $unprotected_header = $instruction->getUnprotectedHeader();
     $complete_header = array_merge($protected_header, $protected_header);
     $jwt_protected_header = empty($protected_header) ? null : Base64Url::encode(json_encode($protected_header));
     $signature_algorithm = $this->getSignatureAlgorithm($complete_header, $instruction->getKey());
     if (!$this->checkKeyUsage($instruction->getKey(), 'signature')) {
         throw new \InvalidArgumentException('Key cannot be used to sign');
     }
     $signature = $signature_algorithm->sign($instruction->getKey(), $jwt_protected_header . '.' . $jwt_payload);
     $jwt_signature = Base64Url::encode($signature);
     $result = ['signature' => $jwt_signature];
     if (null !== $protected_header) {
         $result['protected'] = $jwt_protected_header;
     }
     if (!empty($unprotected_header)) {
         $result['header'] = $unprotected_header;
     }
     return $result;
 }
Ejemplo n.º 22
0
 /**
  * @param string     $type
  * @param string[]   $data
  * @param PrivateKey $privateKey
  *
  * @return ChallengeInterface|null
  */
 public static function create($type, array $data, PrivateKey $privateKey)
 {
     switch ($type) {
         case ChallengeInterface::HTTP_01:
             $challenge = new Http01Challenge();
             break;
         case ChallengeInterface::DNS_01:
             $challenge = new Dns01Challenge();
             break;
         case ChallengeInterface::TLS_SNI_01:
             $challenge = new TlsSni01Challenge();
             break;
         default:
             return;
     }
     $challenge->setToken($data['token']);
     $challenge->setUri($data['uri']);
     $challenge->setStatus(isset($data['status']) ? $data['status'] : null);
     $header = ['e' => Base64Url::encode($privateKey->getDetails()['rsa']['e']), 'kty' => 'RSA', 'n' => Base64Url::encode($privateKey->getDetails()['rsa']['n'])];
     $authorizationKey = $challenge->getToken() . '.' . Base64Url::encode(hash('sha256', json_encode($header), true));
     $challenge->setAuthorizationKey($authorizationKey);
     return $challenge;
 }
 /**
  * {@inheritdoc}
  */
 public function calculateSubjectIdentifier(BaseUserAccountInterface $user_account, $sector_identifier_host)
 {
     $prepared = sprintf('%s:%s:%s', $sector_identifier_host, $user_account->getPublicId(), $this->salt);
     return Base64Url::encode(openssl_encrypt($prepared, $this->algorithm, $this->pairwise_encryption_key, OPENSSL_RAW_DATA, $this->iv));
 }
 /**
  * @return array
  */
 private function getAdditionalPayload()
 {
     return ['jti' => Base64Url::encode(random_bytes(64)), 'exp' => time() + $this->ttl, 'nbf' => time(), 'iat' => time(), 'iss' => $this->issuer, 'aud' => $this->issuer];
 }
 /**
  * {@inheritdoc}
  */
 protected function createClientSecret()
 {
     return Base64Url::encode(random_bytes(64));
 }
 /**
  * @throws \OAuth2\Exception\BaseExceptionInterface
  *
  * @return string
  */
 private function generateToken()
 {
     $length = $this->getRefreshTokenLength();
     return Base64Url::encode(random_bytes($length));
 }
 public function __construct()
 {
     $this->setPublicId(trim(chunk_split(Base64Url::encode(uniqid(mt_rand(), true)), 16, '-'), '-'));
 }
Ejemplo n.º 28
0
 /**
  * @return \Jose\Object\JWKInterface
  */
 protected function createJWK()
 {
     $data = JWKFactory::createKey($this->parameters)->getAll();
     $data['kid'] = Base64Url::encode(random_bytes(64));
     return JWKFactory::createFromValues($data);
 }
 /**
  * @param string $token
  *
  * @return string
  */
 private function getHash($token)
 {
     return Base64Url::encode(mb_substr(hash($this->getHashMethod(), $token, true), 0, $this->getHashSize(), '8bit'));
 }
 /**
  * @return string
  */
 private function generateNonce()
 {
     $expiry_time = microtime(true) + $this->nonce_lifetime * 1000;
     $signature_value = Base64Url::encode(hash_hmac($this->hash_algorithm, $expiry_time . $this->hash_key, $this->hash_key, true));
     return base64_encode($expiry_time . ':' . $signature_value);
 }