示例#1
0
 async def get_keys2(keys_to_fetch):
     self.assertEqual(keys_to_fetch, {"server1": {get_key_id(key1): 1500}})
     return {
         "server1": {
             get_key_id(key1): FetchKeyResult(get_verify_key(key1), 1200)
         }
     }
示例#2
0
 async def second_lookup_fetch(
         server_name: str, key_ids: List[str],
         minimum_valid_until_ts: int) -> Dict[str, FetchKeyResult]:
     # self.assertEquals(current_context().request.id, "context_12")
     return {
         get_key_id(key1): FetchKeyResult(get_verify_key(key1), 100)
     }
示例#3
0
 async def second_lookup_fetch(keys_to_fetch):
     self.assertEquals(current_context().request, "context_12")
     return {
         "server10": {
             get_key_id(key1): FetchKeyResult(get_verify_key(key1), 100)
         }
     }
示例#4
0
文件: keyring.py 项目: Fnux/synapse
    def __init__(self,
                 hs: "HomeServer",
                 key_fetchers: "Optional[Iterable[KeyFetcher]]" = None):
        self.clock = hs.get_clock()

        if key_fetchers is None:
            key_fetchers = (
                StoreKeyFetcher(hs),
                PerspectivesKeyFetcher(hs),
                ServerKeyFetcher(hs),
            )
        self._key_fetchers = key_fetchers

        self._server_queue: BatchingQueue[_FetchKeyRequest, Dict[str, Dict[
            str, FetchKeyResult]]] = BatchingQueue(
                "keyring_server",
                clock=hs.get_clock(),
                process_batch_callback=self._inner_fetch_key_requests,
            )

        self._hostname = hs.hostname

        # build a FetchKeyResult for each of our own keys, to shortcircuit the
        # fetcher.
        self._local_verify_keys: Dict[str, FetchKeyResult] = {}
        for key_id, key in hs.config.key.old_signing_keys.items():
            self._local_verify_keys[key_id] = FetchKeyResult(
                verify_key=key, valid_until_ts=key.expired_ts)

        vk = get_verify_key(hs.signing_key)
        self._local_verify_keys[f"{vk.alg}:{vk.version}"] = FetchKeyResult(
            verify_key=vk,
            valid_until_ts=2**63,  # fake future timestamp
        )
示例#5
0
        async def get_keys(keys_to_fetch):
            # there should only be one request object (with the max validity)
            self.assertEqual(keys_to_fetch, {"server1": {get_key_id(key1): 1500}})

            return {
                "server1": {
                    get_key_id(key1): FetchKeyResult(get_verify_key(key1), 1200)
                }
            }
示例#6
0
 async def get_keys2(
         server_name: str, key_ids: List[str],
         minimum_valid_until_ts: int) -> Dict[str, FetchKeyResult]:
     self.assertEqual(server_name, "server1")
     self.assertEqual(key_ids, [get_key_id(key1)])
     self.assertEqual(minimum_valid_until_ts, 1500)
     return {
         get_key_id(key1): FetchKeyResult(get_verify_key(key1), 1200)
     }
示例#7
0
 def get_keys1(keys_to_fetch):
     self.assertEqual(keys_to_fetch, {"server1": {get_key_id(key1): 1500}})
     return defer.succeed(
         {
             "server1": {
                 get_key_id(key1): FetchKeyResult(get_verify_key(key1), 800)
             }
         }
     )
示例#8
0
        async def get_keys(
                server_name: str, key_ids: List[str],
                minimum_valid_until_ts: int) -> Dict[str, FetchKeyResult]:
            self.assertEqual(server_name, self.hs.hostname)
            self.assertEqual(key_ids, [get_key_id(key2)])

            return {
                get_key_id(key2): FetchKeyResult(get_verify_key(key2), 1200)
            }
示例#9
0
        async def first_lookup_fetch(keys_to_fetch):
            self.assertEquals(current_context().request, "context_11")
            self.assertEqual(keys_to_fetch, {"server10": {get_key_id(key1): 0}})

            await make_deferred_yieldable(first_lookup_deferred)
            return {
                "server10": {
                    get_key_id(key1): FetchKeyResult(get_verify_key(key1), 100)
                }
            }
示例#10
0
        async def get_keys(
                server_name: str, key_ids: List[str],
                minimum_valid_until_ts: int) -> Dict[str, FetchKeyResult]:
            # there should only be one request object (with the max validity)
            self.assertEqual(server_name, "server1")
            self.assertEqual(key_ids, [get_key_id(key1)])
            self.assertEqual(minimum_valid_until_ts, 1500)

            return {
                get_key_id(key1): FetchKeyResult(get_verify_key(key1), 1200)
            }
示例#11
0
        async def first_lookup_fetch(
                server_name: str, key_ids: List[str],
                minimum_valid_until_ts: int) -> Dict[str, FetchKeyResult]:
            # self.assertEquals(current_context().request.id, "context_11")
            self.assertEqual(server_name, "server10")
            self.assertEqual(key_ids, [get_key_id(key1)])
            self.assertEqual(minimum_valid_until_ts, 0)

            await make_deferred_yieldable(first_lookup_deferred)
            return {
                get_key_id(key1): FetchKeyResult(get_verify_key(key1), 100)
            }
示例#12
0
def main() -> None:
    parser = argparse.ArgumentParser()

    parser.add_argument(
        "key_file",
        nargs="+",
        type=argparse.FileType("r"),
        help="The key file to read",
    )

    parser.add_argument(
        "-x",
        action="store_true",
        dest="for_config",
        help=
        "format the output for inclusion in the old_signing_keys config setting",
    )

    parser.add_argument(
        "--expiry-ts",
        type=int,
        default=int(time.time() * 1000) + 6 * 3600000,
        help=
        ("The expiry time to use for -x, in milliseconds since 1970. The default "
         "is (now+6h)."),
    )

    args = parser.parse_args()

    formatter = ((lambda k: format_for_config(k, args.expiry_ts))
                 if args.for_config else format_plain)

    for file in args.key_file:
        try:
            res = read_signing_keys(file)
        except Exception as e:
            exit(
                status=1,
                message="Error reading key from file %s: %s %s" %
                (file.name, type(e), e),
            )
        for key in res:
            formatter(get_verify_key(key))
示例#13
0
    def test_verify_json_for_server_with_null_valid_until_ms(self):
        """Tests that we correctly handle key requests for keys we've stored
        with a null `ts_valid_until_ms`
        """
        mock_fetcher = keyring.KeyFetcher()
        mock_fetcher.get_keys = Mock(return_value=defer.succeed({}))

        kr = keyring.Keyring(
            self.hs, key_fetchers=(StoreKeyFetcher(self.hs), mock_fetcher)
        )

        key1 = signedjson.key.generate_signing_key(1)
        r = self.hs.datastore.store_server_verify_keys(
            "server9",
            time.time() * 1000,
            [("server9", get_key_id(key1), FetchKeyResult(get_verify_key(key1), None))],
        )
        self.get_success(r)

        json1 = {}
        signedjson.sign.sign_json(json1, "server9", key1)

        # should fail immediately on an unsigned object
        d = _verify_json_for_server(kr, "server9", {}, 0, "test unsigned")
        self.failureResultOf(d, SynapseError)

        # should fail on a signed object with a non-zero minimum_valid_until_ms,
        # as it tries to refetch the keys and fails.
        d = _verify_json_for_server(
            kr, "server9", json1, 500, "test signed non-zero min"
        )
        self.get_failure(d, SynapseError)

        # We expect the keyring tried to refetch the key once.
        mock_fetcher.get_keys.assert_called_once_with(
            {"server9": {get_key_id(key1): 500}}
        )

        # should succeed on a signed object with a 0 minimum_valid_until_ms
        d = _verify_json_for_server(
            kr, "server9", json1, 0, "test signed with zero min"
        )
        self.get_success(d)
示例#14
0
    def __init__(self,
                 hs: "HomeServer",
                 key_fetchers: "Optional[Iterable[KeyFetcher]]" = None):
        self.clock = hs.get_clock()

        if key_fetchers is None:
            key_fetchers = (
                StoreKeyFetcher(hs),
                PerspectivesKeyFetcher(hs),
                ServerKeyFetcher(hs),
            )
        self._key_fetchers = key_fetchers

        self._server_queue: BatchingQueue[_FetchKeyRequest, Dict[str, Dict[
            str, FetchKeyResult]]] = BatchingQueue(
                "keyring_server",
                clock=hs.get_clock(),
                process_batch_callback=self._inner_fetch_key_requests,
            )
        self.verify_key = get_verify_key(hs.signing_key)
        self.hostname = hs.hostname
示例#15
0
    def test_verify_json_for_server(self):
        kr = keyring.Keyring(self.hs)

        key1 = signedjson.key.generate_signing_key(1)
        r = self.hs.datastore.store_server_verify_keys(
            "server9",
            time.time() * 1000,
            [("server9", get_key_id(key1), FetchKeyResult(get_verify_key(key1), 1000))],
        )
        self.get_success(r)

        json1 = {}
        signedjson.sign.sign_json(json1, "server9", key1)

        # should fail immediately on an unsigned object
        d = _verify_json_for_server(kr, "server9", {}, 0, "test unsigned")
        self.failureResultOf(d, SynapseError)

        # should suceed on a signed object
        d = _verify_json_for_server(kr, "server9", json1, 500, "test signed")
        # self.assertFalse(d.called)
        self.get_success(d)
示例#16
0
def encode_pubkey(sk: SigningKey) -> str:
    """Encode the public key corresponding to the given signing key as base64"""
    return key.encode_verify_key_base64(key.get_verify_key(sk))
        y = arr
      else:
        return sum(arr) 


print(summer_69([1, 3, 5]))
print(summer_69([4, 5, 6, 7, 8, 9]))
print(summer_69([2, 1, 6, 9, 11]))
print(summer_69([]))
'''
print("\n")
from signedjson.key import generate_signing_key, get_verify_key, encode_signing_key_base64
from signedjson.sign import (
    sign_json, verify_signed_json, SignatureVerifyException
)

signing_key = generate_signing_key('zxcvb')
base_64_signing_key = encode_signing_key_base64(signing_key)
print(base_64_signing_key)
signed_json = sign_json({'my_key': 'my_data'},'Drew', signing_key)
print(signed_json)
verify_key = get_verify_key(signing_key)
base_64_verify_key = encode_signing_key_base64(verify_key)
print(base_64_verify_key)
#check = get_verify_key(base_64_signing_key)

try:
    verify_signed_json(signed_json, 'Drew', verify_key)
    print('Signature is valid')
except SignatureVerifyException:
    print('Signature is invalid')
示例#18
0
 def setUp(self):
     self.version = "my_version"
     self.key = generate_signing_key(self.version)
     self.key_base64 = encode_signing_key_base64(self.key)
     self.verify_key = get_verify_key(self.key)
     self.verify_key_base64 = encode_verify_key_base64(self.verify_key)
示例#19
0
 def setUp(self):
     self.version = "my_version"
     self.key = generate_signing_key(self.version)
     self.key_base64 = encode_signing_key_base64(self.key)
     self.verify_key = get_verify_key(self.key)
     self.verify_key_base64 = encode_verify_key_base64(self.verify_key)