Exemplo n.º 1
0
 /**
  * {@inheritdoc}
  */
 public function getCEK(JWKInterface $key, array $header)
 {
     if ('dir' !== $key->getKeyType()) {
         throw new \InvalidArgumentException('The key is not valid');
     }
     return Base64Url::decode($key->getValue('dir'));
 }
Exemplo n.º 2
0
 /**
  * @param \Jose\Object\JWSInterface $jws
  * @param array                     $data
  */
 private static function populatePayload(JWSInterface &$jws, array $data)
 {
     $is_encoded = null;
     foreach ($jws->getSignatures() as $signature) {
         if (null === $is_encoded) {
             $is_encoded = self::isPayloadEncoded($signature);
         }
         Assertion::eq($is_encoded, self::isPayloadEncoded($signature), 'Foreign payload encoding detected. The JWS cannot be loaded.');
     }
     if (array_key_exists('payload', $data)) {
         $payload = $data['payload'];
         $jws = $jws->withAttachedPayload();
         $jws = $jws->withEncodedPayload($payload);
         if (false !== $is_encoded) {
             $payload = Base64Url::decode($payload);
         }
         $json = json_decode($payload, true);
         if (null !== $json && !empty($payload)) {
             $payload = $json;
         }
         $jws = $jws->withPayload($payload);
     } else {
         $jws = $jws->withDetachedPayload();
     }
 }
Exemplo n.º 3
0
 /**
  *
  */
 public function testValidCEK()
 {
     $header = [];
     $key = new JWK(['kty' => 'dir', 'dir' => Base64Url::encode('ABCD')]);
     $dir = new Dir();
     $this->assertEquals('ABCD', $dir->getCEK($key, $header));
 }
Exemplo n.º 4
0
 /**
  * @param JWKInterface $key
  */
 protected function checkKey(JWKInterface $key)
 {
     parent::checkKey($key);
     if (24 !== strlen(Base64Url::decode($key->getValue('k')))) {
         throw new \InvalidArgumentException('The key size is not valid');
     }
 }
Exemplo n.º 5
0
 /**
  * {@inheritdoc}
  */
 public function getCEK(JWKInterface $key, array $header)
 {
     if (!$key->has('kty') || 'dir' !== $key->get('kty') || !$key->has('dir')) {
         throw new \InvalidArgumentException('The key is not valid');
     }
     return Base64Url::decode($key->get('dir'));
 }
 /**
  * {@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);
 }
Exemplo n.º 7
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));
 }
Exemplo n.º 8
0
 /**
  * JWS constructor.
  *
  * @param string      $input
  * @param string      $signature
  * @param string|null $encoded_payload
  * @param string|null $payload
  * @param string|null $encoded_protected_header
  * @param array       $unprotected_headers
  */
 public function __construct($input, $signature, $encoded_payload = null, $payload = null, $encoded_protected_header = null, array $unprotected_headers = [])
 {
     $protected_header = empty($encoded_protected_header) ? [] : json_decode(Base64Url::decode($encoded_protected_header), true);
     parent::__construct($input, $protected_header, $unprotected_headers, $payload);
     $this->signature = $signature;
     $this->encoded_payload = $encoded_payload;
     $this->encoded_protected_header = $encoded_protected_header;
 }
 /**
  * {@inheritdoc}
  */
 public function getPublicIdFromSubjectIdentifier($subject_identifier)
 {
     $decoded = openssl_decrypt(Base64Url::decode($subject_identifier), $this->algorithm, $this->pairwise_encryption_key, OPENSSL_RAW_DATA, $this->iv);
     $parts = explode(':', $decoded);
     if (3 !== count($parts)) {
         return;
     }
     return $parts[1];
 }
Exemplo n.º 10
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));
 }
Exemplo n.º 11
0
 /**
  * @param \Jose\Object\JWKInterface $key
  */
 protected function checkKey(JWKInterface $key)
 {
     if (!$key->has('kty') || 'oct' !== $key->get('kty') || !$key->has('k')) {
         throw new \InvalidArgumentException('The key is not valid');
     }
     if ($this->getKeySize() !== strlen(Base64Url::decode($key->get('k')))) {
         throw new \InvalidArgumentException('The key size is not valid');
     }
 }
Exemplo n.º 12
0
 /**
  * Key Derivation Function.
  *
  * @param string $Z                   Shared secret
  * @param string $algorithm           Encryption algorithm
  * @param int    $encryption_key_size Size of the encryption key
  * @param string $apu                 Agreement PartyUInfo (information about the producer)
  * @param string $apv                 Agreement PartyVInfo (information about the recipient)
  *
  * @return string
  */
 public static function generate($Z, $algorithm, $encryption_key_size, $apu = '', $apv = '')
 {
     $apu = !empty($apu) ? Base64Url::decode($apu) : '';
     $apv = !empty($apv) ? Base64Url::decode($apv) : '';
     $encryption_segments = [self::toInt32Bits(1), $Z, self::toInt32Bits(mb_strlen($algorithm, '8bit')) . $algorithm, self::toInt32Bits(mb_strlen($apu, '8bit')) . $apu, self::toInt32Bits(mb_strlen($apv, '8bit')) . $apv, self::toInt32Bits($encryption_key_size), ''];
     $input = implode('', $encryption_segments);
     $hash = hash('sha256', $input, true);
     $kdf = mb_substr($hash, 0, $encryption_key_size / 8, '8bit');
     return $kdf;
 }
Exemplo n.º 13
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));
 }
Exemplo n.º 14
0
 /**
  *
  */
 public function testES512Verify()
 {
     $public_key = new JWK();
     $public_key->setValues(['kty' => 'EC', 'kid' => '*****@*****.**', 'use' => 'sig', 'crv' => 'P-521', 'x' => 'AHKZLLOsCOzz5cY97ewNUajB957y-C-U88c3v13nmGZx6sYl_oJXu9A5RkTKqjqvjyekWF-7ytDyRXYgCF5cj0Kt', 'y' => 'AdymlHvOiLxXkEhayXQnNCvDX4h9htZaCJN34kfmC6pV5OhQHiraVySsUdaQkAgDPrwQrJmbnX9cwlGfP-HqHZR1']);
     $header = 'eyJhbGciOiJFUzUxMiIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhbXBsZSJ9';
     $payload = 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4';
     $signature = 'AE_R_YZCChjn4791jSQCrdPZCNYqHXCTZH0-JZGYNlaAjP2kqaluUIIUnC9qvbu9Plon7KRTzoNEuT4Va2cmL1eJAQy3mtPBu_u_sDDyYjnAMDxXPn7XrT0lw-kvAD890jl8e2puQens_IEKBpHABlsbEPX6sFY8OcGDqoRuBomu9xQ2';
     $ecdsa = new ES512();
     $this->assertTrue($ecdsa->verify($public_key, $header . '.' . $payload, Base64Url::decode($signature)));
 }
Exemplo n.º 15
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));
 }
Exemplo n.º 16
0
 /**
  * @param \Jose\Object\JWKInterface $key
  * @param string                    $encryted_cek
  * @param array                     $header
  *
  * @return mixed
  */
 public function decryptKey(JWKInterface $key, $encryted_cek, array $header)
 {
     $this->checkKey($key);
     $this->checkAdditionalParameters($header);
     $cipher = Cipher::aes(Cipher::MODE_GCM, $this->getKeySize());
     $cipher->setTag(Base64Url::decode($header['tag']));
     $cipher->setAAD(null);
     $cek = $cipher->decrypt($encryted_cek, Base64Url::decode($key->get('k')), Base64Url::decode($header['iv']));
     return $cek;
 }
Exemplo n.º 17
0
 /**
  * {@inheritdoc}
  */
 public function verify(JWKInterface $key, $data, $signature)
 {
     $this->checkKey($key);
     $public = Base64Url::decode($key->get('x'));
     switch ($key->get('crv')) {
         case 'Ed25519':
             return ed25519_sign_open($data, $public, $signature);
         default:
             throw new \InvalidArgumentException('Unsupported curve');
     }
 }
Exemplo n.º 18
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);
 }
 /**
  *
  */
 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));
 }
Exemplo n.º 20
0
 public static function handle_register()
 {
     if (isset($_POST['oldEndpoint']) && $_POST['oldEndpoint'] !== $_POST['endpoint']) {
         WebPush_DB::remove_subscription($_POST['oldEndpoint']);
     }
     WebPush_DB::add_subscription($_POST['endpoint'], isset($_POST['key']) ? $_POST['key'] : '', isset($_POST['auth']) ? Base64Url::decode($_POST['auth']) : '');
     if (isset($_POST['newRegistration'])) {
         update_option('webpush_accepted_prompt_count', get_option('webpush_accepted_prompt_count') + 1);
     }
     wp_die();
 }
Exemplo n.º 21
0
 /**
  * JWE constructor.
  *
  * @param string      $input
  * @param string      $ciphertext
  * @param string|null $encrypted_key
  * @param string|null $iv
  * @param string|null $aad
  * @param string|null $tag
  * @param string|null $encoded_protected_header
  * @param array       $unprotected_header
  * @param string|null $payload
  */
 public function __construct($input, $ciphertext, $encrypted_key = null, $iv = null, $aad = null, $tag = null, $encoded_protected_header = null, $unprotected_header = [], $payload = null)
 {
     $protected_header = empty($encoded_protected_header) ? [] : json_decode(Base64Url::decode($encoded_protected_header), true);
     parent::__construct($input, $protected_header, $unprotected_header, $payload);
     $this->ciphertext = $ciphertext;
     $this->encrypted_key = $encrypted_key;
     $this->iv = $iv;
     $this->aad = $aad;
     $this->tag = $tag;
     $this->encoded_protected_header = $encoded_protected_header;
 }
 /**
  * @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));
 }
Exemplo n.º 23
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));
 }
Exemplo n.º 24
0
 /**
  * {@inheritdoc}
  */
 public function unwrapKey(JWKInterface $key, $encrypted_cek, array $header)
 {
     $this->checkKey($key);
     $this->checkHeaderAlgorithm($header);
     $this->checkHeaderAdditionalParameters($header);
     $wrapper = $this->getWrapper();
     $hash_algorithm = $this->getHashAlgorithm();
     $key_size = $this->getKeySize();
     $salt = $header['alg'] . "" . Base64Url::decode($header['p2s']);
     $count = $header['p2c'];
     $password = Base64Url::decode($key->get('k'));
     $derived_key = hash_pbkdf2($hash_algorithm, $password, $salt, $count, $key_size, true);
     return $wrapper->unwrap($derived_key, $encrypted_cek);
 }
Exemplo n.º 25
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())));
 }
Exemplo n.º 26
0
 /**
  * @see https://tools.ietf.org/html/rfc7518#appendix-C
  */
 public function testGetAgreementKey()
 {
     $receiver = new JWK(['kty' => 'EC', 'crv' => 'P-256', 'x' => 'weNJy2HscCSM6AEDTDg04biOvhFhyyWvOHQfeF_PxMQ', 'y' => 'e8lnCO-AlStT-NJVX-crhB7QRYhiix03illJOVAOyck', 'd' => 'VEmDZpDXXK8p8N0Cndsxs924q6nS1RXFASRl6BfUqdw']);
     $sender = new JWK(['kty' => 'EC', 'crv' => 'P-256', 'x' => 'gI0GAILBdu7T53akrFmMyGcsF3n5dO7MmwNBHKW5SV0', 'y' => 'SLW_xSffzlPWrHEVI30DHM_4egVwt3NQqeUD7nMFpps', 'd' => '0_NxaRPUMQoAJt50Gz8YiTr8gRTwyEaCumd']);
     $header = ['enc' => 'A128GCM', 'apu' => 'QWxpY2U', 'apv' => 'Qm9i'];
     $expected = Base64Url::decode('9FdsD3uzmeK4ImyoWpP5PA');
     $ecdh_es = new ECDHES();
     $additional_header_values = [];
     $this->assertEquals($expected, $ecdh_es->getAgreementKey(128, $sender, $receiver, $header, $additional_header_values));
     $this->assertTrue(array_key_exists('epk', $additional_header_values));
     $this->assertTrue(array_key_exists('kty', $additional_header_values['epk']));
     $this->assertTrue(array_key_exists('crv', $additional_header_values['epk']));
     $this->assertTrue(array_key_exists('x', $additional_header_values['epk']));
     $this->assertTrue(array_key_exists('y', $additional_header_values['epk']));
 }
Exemplo n.º 27
0
 /**
  * @see https://tools.ietf.org/html/rfc7516#appendix-A.1
  */
 public function testRSAOAEPEncryptionAndDecryption()
 {
     $header = [];
     $jwk = new JWK(['kty' => 'RSA', 'n' => 'oahUIoWw0K0usKNuOR6H4wkf4oBUXHTxRvgb48E-BVvxkeDNjbC4he8rUWcJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3Spsk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2asbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMStPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2djYgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw', 'e' => 'AQAB', 'd' => 'kLdtIj6GbDks_ApCSTYQtelcNttlKiOyPzMrXHeI-yk1F7-kpDxY4-WY5NWV5KntaEeXS1j82E375xxhWMHXyvjYecPT9fpwR_M9gV8n9Hrh2anTpTD93Dt62ypW3yDsJzBnTnrYu1iwWRgBKrEYY46qAZIrA2xAwnm2X7uGR1hghkqDp0Vqj3kbSCz1XyfCs6_LehBwtxHIyh8Ripy40p24moOAbgxVw3rxT_vlt3UVe4WO3JkJOzlpUf-KTVI2Ptgm-dARxTEtE-id-4OJr0h-K-VFs3VSndVTIznSxfyrj8ILL6MG_Uv8YAu7VILSB3lOW085-4qE3DzgrTjgyQ', 'p' => '1r52Xk46c-LsfB5P442p7atdPUrxQSy4mti_tZI3Mgf2EuFVbUoDBvaRQ-SWxkbkmoEzL7JXroSBjSrK3YIQgYdMgyAEPTPjXv_hI2_1eTSPVZfzL0lffNn03IXqWF5MDFuoUYE0hzb2vhrlN_rKrbfDIwUbTrjjgieRbwC6Cl0', 'q' => 'wLb35x7hmQWZsWJmB_vle87ihgZ19S8lBEROLIsZG4ayZVe9Hi9gDVCOBmUDdaDYVTSNx_8Fyw1YYa9XGrGnDew00J28cRUoeBB_jKI1oma0Orv1T9aXIWxKwd4gvxFImOWr3QRL9KEBRzk2RatUBnmDZJTIAfwTs0g68UZHvtc', 'dp' => 'ZK-YwE7diUh0qR1tR7w8WHtolDx3MZ_OTowiFvgfeQ3SiresXjm9gZ5KLhMXvo-uz-KUJWDxS5pFQ_M0evdo1dKiRTjVw_x4NyqyXPM5nULPkcpU827rnpZzAJKpdhWAgqrXGKAECQH0Xt4taznjnd_zVpAmZZq60WPMBMfKcuE', 'dq' => 'Dq0gfgJ1DdFGXiLvQEZnuKEN0UUmsJBxkjydc3j4ZYdBiMRAy86x0vHCjywcMlYYg4yoC4YZa9hNVcsjqA3FeiL19rk8g6Qn29Tt0cj8qqyFpz9vNDBUfCAiJVeESOjJDZPYHdHY8v1b-o-Z2X5tvLx-TCekf7oxyeKDUqKWjis', 'qi' => 'VIMpMYbPf47dT1w_zDUXfPimsSegnMOA1zTaX7aGk_8urY6R8-ZW1FxU7AlWAyLWybqq6t16VFd7hQd0y6flUK4SlOydB61gwanOsXGOAOv82cHq0E3eL4HrtZkUuKvnPrMnsUUFlfUdybVzxyjz9JF_XyaY14ardLSjf4L_FNY']);
     $cek = [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];
     foreach ($cek as $key => $value) {
         $cek[$key] = str_pad(dechex($value), 2, '0', STR_PAD_LEFT);
     }
     $cek = hex2bin(implode('', $cek));
     $from_specification = Base64Url::decode('OKOawDo13gRp2ojaHV7LFpZcgV7T6DVZKTyKOMTYUmKoTCVJRgckCL9kiMT03JGeipsEdY3mx_etLbbWSrFr05kLzcSr4qKAq7YN7e9jwQRb23nfa6c9d-StnImGyFDbSv04uVuxIp5Zms1gNxKKK2Da14B8S4rzVRltdYwam_lDp5XnZAYpQdb76FdIKLaVmqgfwX7XWRxv2322i-vDxRfqNzo_tETKzpVLzfiwQyeyPGLBIO56YJ7eObdv0je81860ppamavo35UgoRdbYaBcoh9QcfylQr66oc6vFWXRcZ_ZT2LawVCWTIy3brGPi6UklfCpIMfIjf7iGdXKHzg');
     $rsa_oaep = new RSAOAEP();
     $encrypted = $rsa_oaep->encryptKey($jwk, $cek, $header);
     $this->assertEquals($cek, $rsa_oaep->decryptKey($jwk, $encrypted, $header));
     $this->assertEquals($cek, $rsa_oaep->decryptKey($jwk, $from_specification, $header));
 }
Exemplo n.º 28
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;
 }
Exemplo n.º 29
0
 /**
  * {@inheritdoc}
  */
 public function unwrapKey(JWKInterface $key, $encrypted_cek, array $header)
 {
     $this->checkKey($key);
     $this->checkAdditionalParameters($header);
     $kek = Base64Url::decode($key->get('k'));
     $tag = Base64Url::decode($header['tag']);
     $iv = Base64Url::decode($header['iv']);
     if (version_compare(PHP_VERSION, '7.1.0') >= 0) {
         return openssl_decrypt($encrypted_cek, $this->getMode($kek), $kek, OPENSSL_RAW_DATA, $iv, $tag, null);
     } elseif (class_exists('\\Crypto\\Cipher')) {
         $cipher = Cipher::aes(Cipher::MODE_GCM, $this->getKeySize());
         $cipher->setTag($tag);
         $cipher->setAAD(null);
         $cek = $cipher->decrypt($encrypted_cek, $kek, $iv);
         return $cek;
     }
     return AESGCM::decrypt($kek, $iv, $encrypted_cek, null, $tag);
 }
Exemplo n.º 30
0
 /**
  * @param \Jose\Object\JWEInterface                           $jwe
  * @param \Jose\Algorithm\ContentEncryptionAlgorithmInterface $content_encryption_algorithm
  * @param string                                              $key_management_mode
  * @param array                                               $additional_headers
  *
  * @return string
  */
 private function determineCEK(Object\JWEInterface $jwe, Algorithm\ContentEncryptionAlgorithmInterface $content_encryption_algorithm, $key_management_mode, array &$additional_headers)
 {
     switch ($key_management_mode) {
         case Algorithm\KeyEncryption\KeyEncryptionInterface::MODE_ENCRYPT:
         case Algorithm\KeyEncryption\KeyEncryptionInterface::MODE_WRAP:
             return $this->createCEK($content_encryption_algorithm->getCEKSize());
         case Algorithm\KeyEncryption\KeyEncryptionInterface::MODE_AGREEMENT:
             Assertion::eq(1, $jwe->countRecipients(), 'Unable to encrypt for multiple recipients using key agreement algorithms.');
             $complete_headers = array_merge($jwe->getSharedProtectedHeaders(), $jwe->getSharedHeaders(), $jwe->getRecipient(0)->getHeaders());
             $algorithm = $this->findKeyEncryptionAlgorithm($complete_headers);
             return $algorithm->getAgreementKey($content_encryption_algorithm->getCEKSize(), $content_encryption_algorithm->getAlgorithmName(), $jwe->getRecipient(0)->getRecipientKey(), $complete_headers, $additional_headers);
         case Algorithm\KeyEncryption\KeyEncryptionInterface::MODE_DIRECT:
             Assertion::eq(1, $jwe->countRecipients(), 'Unable to encrypt for multiple recipients using key agreement algorithms.');
             Assertion::eq($jwe->getRecipient(0)->getRecipientKey()->get('kty'), 'oct', 'Wrong key type.');
             Assertion::true($jwe->getRecipient(0)->getRecipientKey()->has('k'), 'The key parameter "k" is missing.');
             return Base64Url::decode($jwe->getRecipient(0)->getRecipientKey()->get('k'));
         default:
             throw new \InvalidArgumentException(sprintf('Unsupported key management mode "%s".', $key_management_mode));
     }
 }