def test_get_records(self, kinesis_client, kinesis_create_stream, wait_for_stream_ready): stream_name = "test-%s" % short_uid() kinesis_create_stream(StreamName=stream_name, ShardCount=1) wait_for_stream_ready(stream_name) kinesis_client.put_records( StreamName=stream_name, Records=[{ "Data": "SGVsbG8gd29ybGQ=", "PartitionKey": "1" }], ) # get records with JSON encoding iterator = self._get_shard_iterator(stream_name, kinesis_client) response = kinesis_client.get_records(ShardIterator=iterator) json_records = response.get("Records") assert 1 == len(json_records) assert "Data" in json_records[0] # get records with CBOR encoding iterator = self._get_shard_iterator(stream_name, kinesis_client) url = config.get_edge_url() headers = aws_stack.mock_aws_request_headers("kinesis") headers["Content-Type"] = constants.APPLICATION_AMZ_CBOR_1_1 headers["X-Amz-Target"] = "Kinesis_20131202.GetRecords" data = cbor2.dumps({"ShardIterator": iterator}) result = requests.post(url, data, headers=headers) assert 200 == result.status_code result = cbor2.loads(result.content) attrs = ("Data", "EncryptionType", "PartitionKey", "SequenceNumber") assert select_attributes(json_records[0], attrs) == select_attributes( result["Records"][0], attrs)
def encrypt(self, payload: bytes): piv = bytes([self.sequence_number]) kid = self.sender_id protected_header = b'' unprotected_header = {Header.PARTIAL_IV: piv, Header.KID: kid} # Compute sender key and nonce for this particular message key = self.sender_key() nonce = bytes([len(self.sender_id)]) + self.sender_id.rjust(7, b'\0') + bytes([self.sequence_number]).rjust(5, b'\0') nonce = bxor(nonce, self.common_iv()) # Increase sequence number => nonce is always unique self.sequence_number += 1 aad = dumps([piv, kid]) # Encrypt message return Encrypt0Message( plaintext=payload, protected_header=protected_header, unprotected_header=unprotected_header, external_aad=aad ).serialize(iv=nonce, key=key)
def test_raises_exception_on_unsupported_attestation_type(self) -> None: cred_json = { "id": "FsWBrFcw8yRjxV8z18Egh91o1AScNRYkIuUoY6wIlIhslDpP7eydKi1q5s9g1ugDP9mqBlPDDFPRbH6YLwHbtg", "rawId": "FsWBrFcw8yRjxV8z18Egh91o1AScNRYkIuUoY6wIlIhslDpP7eydKi1q5s9g1ugDP9mqBlPDDFPRbH6YLwHbtg", "response": { "attestationObject": "o2NmbXRmcGFja2VkZ2F0dFN0bXSjY2FsZyZjc2lnWEcwRQIgRpuZ6hdaLAgWgCFTIo4BGSTBAxwwqk4u3s1-JAzv_H4CIQCZnfoic34aOwlac1A09eflEtb0V1kO7yGhHOw5P5wVWmN4NWOBWQLBMIICvTCCAaWgAwIBAgIEKudiYzANBgkqhkiG9w0BAQsFADAuMSwwKgYDVQQDEyNZdWJpY28gVTJGIFJvb3QgQ0EgU2VyaWFsIDQ1NzIwMDYzMTAgFw0xNDA4MDEwMDAwMDBaGA8yMDUwMDkwNDAwMDAwMFowbjELMAkGA1UEBhMCU0UxEjAQBgNVBAoMCVl1YmljbyBBQjEiMCAGA1UECwwZQXV0aGVudGljYXRvciBBdHRlc3RhdGlvbjEnMCUGA1UEAwweWXViaWNvIFUyRiBFRSBTZXJpYWwgNzE5ODA3MDc1MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEKgOGXmBD2Z4R_xCqJVRXhL8Jr45rHjsyFykhb1USGozZENOZ3cdovf5Ke8fj2rxi5tJGn_VnW4_6iQzKdIaeP6NsMGowIgYJKwYBBAGCxAoCBBUxLjMuNi4xLjQuMS40MTQ4Mi4xLjEwEwYLKwYBBAGC5RwCAQEEBAMCBDAwIQYLKwYBBAGC5RwBAQQEEgQQbUS6m_bsLkm5MAyP6SDLczAMBgNVHRMBAf8EAjAAMA0GCSqGSIb3DQEBCwUAA4IBAQByV9A83MPhFWmEkNb4DvlbUwcjc9nmRzJjKxHc3HeK7GvVkm0H4XucVDB4jeMvTke0WHb_jFUiApvpOHh5VyMx5ydwFoKKcRs5x0_WwSWL0eTZ5WbVcHkDR9pSNcA_D_5AsUKOBcbpF5nkdVRxaQHuuIuwV4k1iK2IqtMNcU8vL6w21U261xCcWwJ6sMq4zzVO8QCKCQhsoIaWrwz828GDmPzfAjFsJiLJXuYivdHACkeJ5KHMt0mjVLpfJ2BCML7_rgbmvwL7wBW80VHfNdcKmKjkLcpEiPzwcQQhiN_qHV90t-p4iyr5xRSpurlP5zic2hlRkLKxMH2_kRjhqSn4aGF1dGhEYXRhWMRJlg3liA6MaHQ0Fw9kdmBbj-SuuaKGMseZXPO6gx2XY0UAAAAqbUS6m_bsLkm5MAyP6SDLcwBAFsWBrFcw8yRjxV8z18Egh91o1AScNRYkIuUoY6wIlIhslDpP7eydKi1q5s9g1ugDP9mqBlPDDFPRbH6YLwHbtqUBAgMmIAEhWCAq3y0RWh8nLzanBZQwTA7yAbUy9KEDAM0b3N9Elrb0VCJYIJrX7ygtpyInb5mXBE7g9YEow6xWrJ400HhL2r4q5tzV", "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoicERSbWtkZHVBaS1BVTJ4Nm8tRnFxaEkzWEsybmxWbHNDU3IwNHpXa050djg0SndyTUh0RWxSSEhVV0xFRGhrckVhUThCMWxCY0lIX1ZTUnFwX1JBQXciLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjUwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9", }, "type": "public-key", "clientExtensionResults": {}, "transports": ["nfc", "usb"], } # Take the otherwise legitimate credential and mangle its attestationObject's # "fmt" to something it could never actually be parsed_atte_obj = cbor2.loads(base64url_to_bytes(cred_json["response"]["attestationObject"])) # type: ignore parsed_atte_obj["fmt"] = "not_real_fmt" cred_json["response"]["attestationObject"] = bytes_to_base64url(cbor2.dumps(parsed_atte_obj)) # type: ignore credential = RegistrationCredential.parse_raw(json.dumps(cred_json)) challenge = base64url_to_bytes( "pDRmkdduAi-AU2x6o-FqqhI3XK2nlVlsCSr04zWkNtv84JwrMHtElRHHUWLEDhkrEaQ8B1lBcIH_VSRqp_RAAw" ) rp_id = "localhost" expected_origin = "http://localhost:5000" with self.assertRaisesRegex( Exception, "value is not a valid enumeration member" ): verify_registration_response( credential=credential, expected_challenge=challenge, expected_origin=expected_origin, expected_rp_id=rp_id, )
def data_3(self) -> CBOR: """ Create the data_3 message part from EDHOC message 3. """ if self.conn_idr == b'': return self.conn_idr else: return cbor2.dumps(EdhocMessage.encode_bstr_id(self.conn_idr))
def _th4_input(self) -> CBOR: hash_func = config_cose(self.cipher_suite.hash).hash input_th = [ self.transcript(hash_func, self._th3_input), self.msg_3.ciphertext ] return b''.join([cbor2.dumps(part) for part in input_th])
async def send_to_coap(payload): """ POST request to: localhost port 5683 (official IANA assigned CoAP port), URI "/other/sensor-values". """ from aiocoap import Context, Message from aiocoap.numbers.codes import Code from cbor2 import dumps context = await Context.create_client_context() request = Message(payload=dumps(payload), code=Code.POST) request.opt.uri_host = arg_host request.opt.uri_port = arg_port request.opt.uri_path = ("other", "sensor-values") response = await context.request(request).response str_res = str(response.code) status_code = str_res[:4] # or str_res.split()[0] if status_code == "4.00" or status_code == "5.00": print("Error: ", str_res) return False return True
def test_encrypt_key_agreement_key_wrap_decoding( test_encrypt_key_agreement_key_wrap_files): test_input = test_encrypt_key_agreement_key_wrap_files['input'] test_output = test_encrypt_key_agreement_key_wrap_files['output'] msg = CoseMessage.decode(cbor2.dumps((test_output['result']))) assert msg.phdr == test_input['protected'] assert msg.uhdr == test_input['unprotected'] assert msg._enc_structure == test_output['structure'] # test intermediate results for i, (r, r_output) in enumerate( zip(msg.recipients, test_output['recipients'])): # this should actually be static_receiver_key but the test vector is wrong and messed it up r.key = test_input['recipients'][i]['static_receiver_key'] assert r.phdr_encoded == r_output['protected'] assert r.uhdr_encoded == r_output['unprotected'] assert r.payload == r_output['ciphertext'] assert r.get_kdf_context( (r.get_attr(headers.Algorithm) ).get_key_wrap_func()).encode() == r_output['context'] assert r.decrypt((r.get_attr(headers.Algorithm)).get_key_wrap_func()) == \ test_encrypt_key_agreement_key_wrap_files['random_key'].k for r in msg.recipients: assert msg.decrypt(r) == test_input['plaintext']
def register(file, account): """Register a media asset.""" ic = ipfs_client() iscc_result = lib.iscc_from_file(file) iscc_code = iscc_result.pop("iscc") fname = basename(file.name) log.info(f"ISCC-CODE for {fname}: {iscc_code}") # Check for probable ISCC-ID w3 = w3_client() addr = w3.eth.accounts[account] iscc_id = find_next(RegEntry(iscc=iscc_code, actor=addr)) log.info(f"ISCC-ID will probably be: {iscc_id}") iscc_result["filename"] = fname authority = iscc_registry.settings.verification_domain if authority: log.debug(f"Set domain to {authority} in metadata.") iscc_result["domain"] = authority meta_blob = cbor2.dumps(iscc_result) ipfs_result = ic.add(io.BytesIO(meta_blob)) ipfs_cid = ipfs_result["Hash"] log.info(f"CID for {fname} metadata: {ipfs_cid}") if click.confirm(f"Register ISCC-CODE?"): txid = publish(iscc_code, ipfs_cid, account) click.echo(f"Registered ISCC-CODE: {iscc_code}") click.echo(f"Actor wallet address: {addr}") click.echo(f"Registration TX-ID: {txid}") click.echo(f"Probable ISCC-ID: {iscc_id}")
async def _do_join_market(self, member_oid, market_oid, actor_type): assert actor_type in [ActorType.CONSUMER, ActorType.PROVIDER, ActorType.PROVIDER_CONSUMER] member_data = await self.call('network.xbr.console.get_member', member_oid.bytes) member_adr = member_data['address'] config = await self.call('network.xbr.console.get_config') verifyingChain = config['verifying_chain_id'] verifyingContract = binascii.a2b_hex(config['verifying_contract_adr'][2:]) status = await self.call('network.xbr.console.get_status') block_number = status['block']['number'] meta_obj = { } meta_data = cbor2.dumps(meta_obj) h = hashlib.sha256() h.update(meta_data) meta_hash = multihash.to_b58_string(multihash.encode(h.digest(), 'sha2-256')) signature = sign_eip712_market_join(self._ethkey_raw, verifyingChain, verifyingContract, member_adr, block_number, market_oid.bytes, actor_type, meta_hash) request_submitted = await self.call('network.xbr.console.join_market', member_oid.bytes, market_oid.bytes, verifyingChain, block_number, verifyingContract, actor_type, meta_hash, meta_data, signature) vaction_oid = uuid.UUID(bytes=request_submitted['vaction_oid']) self.log.info('SUCCESS! XBR market join request submitted: vaction_oid={vaction_oid}', vaction_oid=vaction_oid)
def encode(self) -> bytes: """ Encodes the COSE key as a CBOR map :return: A COSE key encoded as CBOR map """ return cbor2.dumps(self.store, default=self._custom_cbor_encoder)
def make_diff(obj1, obj2): tok1 = get_cbor_tokens(obj1) tok2 = get_cbor_tokens(obj2) commands = [] diff = { 'v': 1, 'cmds': commands, } sm = difflib.SequenceMatcher(None, tok1, tok2) i_bytes_so_far = 0 j_bytes_so_far = 0 for opcode in sm.get_opcodes(): op, i1, i2, j1, j2 = opcode i_bytes = sum(len(t) for t in tok1[i1:i2]) j_bytes = sum(len(t) for t in tok2[j1:j2]) if op in ('insert', 'replace'): commands.append( [INSERT_BYTES, obj2[j_bytes_so_far:j_bytes_so_far + j_bytes]]) elif op == 'equal': # copy from the original. commands.append( [ORIG_BYTES, i_bytes_so_far, i_bytes_so_far + i_bytes]) else: assert op == 'delete' # don't have to do anything. i_bytes_so_far += i_bytes j_bytes_so_far += j_bytes return cbor2.dumps(diff)
def _th3_input(self) -> CBOR: input_th = [ self.transcript(self.cipher_suite.hash.hash_cls, self._th2_input), self.msg_2.ciphertext ] return b''.join([cbor2.dumps(part) for part in input_th] + [self.data_3])
def send_acme(self, nodeid, msg, is_request): rec = [ RecordType.ACME, msg ] pri_flags = PrimaryBlock.Flag.PAYLOAD_ADMIN if is_request: pri_flags |= ( PrimaryBlock.Flag.REQ_DELETION_REPORT | PrimaryBlock.Flag.USER_APP_ACK ) ctr = BundleContainer() ctr.bundle.primary = PrimaryBlock( bundle_flags=pri_flags, destination=str(nodeid), crc_type=AbstractBlock.CrcType.CRC32, ) ctr.bundle.blocks = [ CanonicalBlock( type_code=1, block_num=1, crc_type=AbstractBlock.CrcType.CRC32, btsd=cbor2.dumps(rec), ), ] self._agent.send_bundle(ctr)
async def render_post(self, request): """ STATUS: + DONE_ match original, test normal. + TODO_ test errors, add bonus error handlers. """ try: await super().render_post(request) except NotAuthorizedException: return aiocoap.Message(code = Code.UNAUTHORIZED) except ThingNotFoundException: return aiocoap.Message(code = Code.NOT_FOUND) else: try: args: dict = loads(self.oscore_context.decrypt(request.payload)) except ValueError: return aiocoap.Message(code = Code.BAD_REQUEST) if self.property_name not in args: return aiocoap.Message(code = Code.BAD_REQUEST) if self.thing.has_property(self.property_name): try: self.thing.set_property(self.property_name, args[self.property_name]) except PropertyError: return aiocoap.Message(code = Code.BAD_REQUEST) response = b'OK' return aiocoap.Message(payload = self.oscore_context.encrypt(dumps(response))) else: return aiocoap.Message(code = Code.NOT_FOUND)
async def render_post(self, request): """ Add action to the internal queue of actions.\n return -- status of action (.as_action_description) STATUS: + DONE_ match original, test normal. + TODO_ test errors, add bonus error handlers. """ try: await super().render_post(request) except NotAuthorizedException: return aiocoap.Message(code = Code.UNAUTHORIZED) except ThingNotFoundException: return aiocoap.Message(code = Code.NOT_FOUND) else: try: args: dict = loads(self.oscore_context.decrypt(request.payload)) except ValueError: return aiocoap.Message(code = Code.BAD_REQUEST) response = {} for name, action_params in args.items(): if name != self.action_name: continue input_ = None if 'input' in action_params: input_ = action_params['input'] action = self.thing.perform_action(name, input_) if action: response.update(action.as_action_description()) action.start() return aiocoap.Message(payload = self.oscore_context.encrypt(dumps(response)))
async def render_get(self, request): """Return stereotype information for the requested Edge server""" if request.opt.content_format != media_types_rev['application/cbor']: raise error.UnsupportedContentFormat() payload = StereotypeRequest.decode(request.payload) if payload.model == TrustModel.No: result = self._no_trust_model(payload) elif payload.model == TrustModel.Basic: result = self._basic_trust_model(payload) elif payload.model == TrustModel.Continuous: result = self._continuous_trust_model(payload) elif payload.model == TrustModel.ChallengeResponse: result = self._challenge_response_trust_model(payload) else: raise error.BadRequest(f"Unknown trust model {payload.model}") result = StereotypeResponse(payload.model, payload.tags, result) result_payload = cbor2.dumps(result.encode()) return aiocoap.Message( payload=result_payload, code=codes.CONTENT, content_format=media_types_rev['application/cbor'])
def validate_meta_data(self, meta, signature): meta_raw = self.meta_convert_raw(meta) stake_pub = self.prefix_bech32("ed25519_pk", self.strip_hex_prefix(meta[2])) sig = self.prefix_bech32("ed25519_sig", self.strip_hex_prefix(signature)) return self.validate_sig(stake_pub, sig, cbor2.dumps(meta_raw))
def create_invalid_cbor(self): ''' Generate a valid-CBOR content which is not really a bundle. :return: A single bundle file. :rtype: file-like ''' return io.BytesIO(cbor2.dumps(randcboritem()))
def test_bad_arrays(self): cddl_spec = '''person = { age: int, name: tstr, employer: tstr, } person_array = [ xage: int, xname: tstr, xemployer: tstr, ]''' bad_arrays = [ [123, 'foo', 'bar', 456], [123, 'foo'], [123], [], ['abc'], ['abc', 123], [123, 'foo', 456], [123, ['foo', 'bar']], [123, ['foo'], 'bar'], ] for index, bad_array in enumerate(bad_arrays): bad_cbor = cbor2.dumps(bad_array) with self.assertRaises(Exception): cddlcat.validate_cbor_bytes('person_array', cddl_spec, bad_cbor)
def describe_pcr(file_handle: typing.TextIO, index: int) -> dict: """Request PCR description from /dev/nsm.""" nsm_key = 'DescribePCR' request_data = cbor2.dumps({nsm_key: {'index': index}}) # Prepare the request and response buffers. The request buffer is the # size of the request data, the response buffer is sized at NSM_RESPONSE_MAX_SIZE. # This code is repeated for every type of request, because moving it to a separate # function creates garbage collection issues. request_buffer = ctypes.create_string_buffer(request_data, len(request_data)) response_buffer = (NSM_RESPONSE_MAX_SIZE * ctypes.c_uint8)() # Prepare a new NsmMessage struct. nsm_message = NsmMessage() # Create new IoVecs pointing to the request and response buffer. _prepare_nsm_message_iovecs(nsm_message, request_buffer, response_buffer) # Send the message to /dev/nsm through an ioctl call. # When the call is complete, the response_buffer will # be filled with response data. _execute_ioctl(file_handle, nsm_message) # Take the CBOR response and translate it to a Python dict. Return the values # for this request's key. decoded_response = _decode_response(nsm_message) if nsm_key not in decoded_response: raise IoctlError(decoded_response.get('Error')) return decoded_response.get(nsm_key)
async def inner(operation, data): if data.request_id is None: data.request_id = UtilInternal.get_request_id() validation = UtilInternal.is_invalid(data) if validation: raise ValidationException(validation) # If we're not connected, immediately try to reconnect if not self.connected: await self.__connect() self.__requests[data.request_id] = asyncio.Queue(1) # Write request to socket frame = MessageFrame(operation=operation, payload=cbor2.dumps(data.as_dict())) for b in UtilInternal.encode_frame(frame): self.__writer.write(b) await self.__writer.drain() # Wait for reader to come back with the response result = await self.__requests[data.request_id].get() # Drop async queue from request map del self.__requests[data.request_id] if isinstance( result, MessageFrame) and result.operation == Operation.Unknown: raise ClientException( "Received response with unknown operation from server") return result
def encode_phdr(self) -> bytes: """ Encode the protected header. """ if len(self._phdr): return cbor2.dumps(self._phdr, default=self._special_cbor_encoder) else: return b''
def test_okp_key_derive_key_with_raw_context(self): with open(key_path("private_key_x25519.pem")) as key_file: private_key = COSEKey.from_pem(key_file.read(), alg="ECDH-SS+HKDF-256") pub_key = COSEKey.from_jwk({ "kty": "OKP", "alg": "ECDH-ES+HKDF-256", "kid": "01", "crv": "X25519", "x": "y3wJq3uXPHeoCO4FubvTc7VcBuqpvUrSvU6ZMbHDTCI", # "d": "vsJ1oX5NNi0IGdwGldiac75r-Utmq3Jq4LGv48Q_Qc4", }) context = [ 1, [None, None, None], [None, None, None], [128, cbor2.dumps({1: -25})], ] try: private_key.derive_key(context, public_key=pub_key) except Exception: pytest.fail("derive_key() should not fail.")
def predict(model_id, img_hash, left, top, right, bottom): left, top, right, bottom = map(int, (left, top, right, bottom)) model = default_network if model_id != "default": model = NeuralNetwork('models/' + model_id + '/input') path = os.path.join(app.config['UPLOAD_FOLDER'], img_hash) if not os.path.isfile(path): print("Image not found:", img_hash) abort(404) print(f"Doing inference with model '{model_id}' and file {img_hash}...") output_img_data, centers = model.get_output_and_centers( path, left, top, right, bottom) if model_id != "default": model.destroy() print(f"Inference complete, now storing result and sending it back...") output_hash = store_in_uploads(output_img_data) result = {'outputImageHash': output_hash, 'cellCenters': centers} result_cbor = cbor2.dumps(result) return result_cbor, 200
def fido2_api_register_begin(request): rp = PublicKeyCredentialRpEntity(get_domain(request), settings.FIDO2_RP_NAME) fido2 = Fido2Server(rp) all_devices = Fido2Device.objects.filter(user=request.user) registration_data, state = fido2.register_begin( { "id": request.user.email.encode(), "name": request.user.email, "displayName": request.user.email, "icon": "", }, # Pass existing fido2 credentials to prevent duplicate credentials=[ AttestedCredentialData(cbor2.loads(d.authenticator_data)) for d in all_devices ], user_verification="discouraged", authenticator_attachment="cross-platform", ) request.session[FIDO2_REGISTER_STATE] = state return HttpResponse(cbor2.dumps(registration_data), content_type="application/octet-stream")
def called(*args): args_bin = cbor2.dumps(args) result_ptr = ffi.new("uint8_t **") result_len = ffi.new("size_t *") callback(ffi.cast("void *", data), ffi.from_buffer(args_bin), len(args_bin), result_ptr, result_len) result = cbor2.loads(bytes(ffi.buffer(result_ptr[0], result_len[0]))) return result
def get_random(file_handle: typing.TextIO, length: int = 32) -> bytes: """Request random bytes from /dev/nsm.""" if length < 1 or length > 256: raise ValueError('GetRandom supports length between 1 and 256 inclusive.') nsm_key = 'GetRandom' request_data = cbor2.dumps(nsm_key) # Prepare the request and response buffers. The request buffer is the # size of the request data, the response buffer is sized at NSM_RESPONSE_MAX_SIZE. # This code is repeated for every type of request, because moving it to a separate # function creates garbage collection issues. request_buffer = ctypes.create_string_buffer(request_data, len(request_data)) response_buffer = (NSM_RESPONSE_MAX_SIZE * ctypes.c_uint8)() # Prepare a new NsmMessage struct. nsm_message = NsmMessage() # Create new IoVecs pointing to the request and response buffer. _prepare_nsm_message_iovecs(nsm_message, request_buffer, response_buffer) # Send the message to /dev/nsm through an ioctl call. # When the call is complete, the response_buffer will # be filled with response data. _execute_ioctl(file_handle, nsm_message) # Read the binary reponse from NSM, fetch the bytes stored under the key 'random' # and return them to the user. decoded_response = _decode_response(nsm_message) random_bytes = decoded_response.get(nsm_key).get('random') if nsm_key not in decoded_response: raise IoctlError(decoded_response.get('Error')) return random_bytes[:length]
def encode(self) -> bytes: info = [ int(self.edhoc_aead_id), self.transcript_hash, self.label, self.length ] info = cbor2.dumps(info) return info
def __init__(self, port): # Create the UDP socket and request the log extensions self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 2 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) self.socket.bind(('', int(port))) broadcasting = True while broadcasting: print("Waiting for broadcaster...") msg, address = self.socket.recvfrom(buffSize) if msg == b'broadcasting_looking_for_other_device': print("Requesting a list the information about the files and their sequence number...") self.socket.sendto(str.encode('requesting_infos_of_all_pcap_files'), address) # 3 broadcasting = False self.__received_package_as_events = [] packet, self.__list_of_needed_extensions = transport.get_i_want_list(self.socket.recv(buffSize)) print("\"I HAVE\"-list received...") self.socket.sendto(packet, address) # 8 print("Sending \"I WANT\"-list...") event_list = self.socket.recv(buffSize) # 11 print("Event list received...") if not cbor2.dumps(event_list): print("You are already up-to-date!") self.__received_package_as_events = event_list self.socket.close()
def write_file(self, d): if self._data is not None: if self._data == d: return self._data = None # Clear cache before writing new data self.write(cbor2.dumps(d)) self._data = d # Update cached data
def coseSig(payload, intermediates, signatures): """Returns the entire (tagged) COSE_Sign structure. payload is a string representing the data to be signed intermediates is an array of byte strings signatures is an array of (algorithm, signingKey, signingCertificate) triplets to be passed to coseSignature """ protected = {KID: intermediates} protectedEncoded = dumps(protected) coseSignatures = [] for (algorithm, signingKey, signingCertificate) in signatures: coseSignatures.append(coseSignature(payload, algorithm, signingKey, signingCertificate, protectedEncoded)) tagged = CBORTag(COSE_Sign, [protectedEncoded, {}, None, coseSignatures]) return dumps(tagged)
def coseSignature(payload, algorithm, signingKey, signingCertificate, bodyProtected): """Returns a COSE_Signature structure. payload is a string representing the data to be signed algorithm is one of (ES256, ES384, ES512) signingKey is a pykey.ECKey to sign the data with signingCertificate is a byte string bodyProtected is the serialized byte string of the protected body header """ protected = {ALG: algorithm, KID: signingCertificate} protectedEncoded = dumps(protected) # Sig_structure = [ # context : "Signature" # body_protected : bodyProtected # sign_protected : protectedEncoded # external_aad : nil # payload : bstr # ] sigStructure = [u'Signature', bodyProtected, protectedEncoded, None, payload] sigStructureEncoded = dumps(sigStructure) pykeyHash = coseAlgorithmToPykeyHash(algorithm) signature = signingKey.signRaw(sigStructureEncoded, pykeyHash) return [protectedEncoded, {}, signature]
def test(): global RESULT user = User() user.oid = 23 user.name = 'Homer Simpson' user.authid = 'homer' user.email = '*****@*****.**' user.birthday = { 'year': 1950, 'month': 12, 'day': 24 } user.is_friendly = True user.tags = [Tag.GEEK, Tag.VIP] #data = json.dumps(user.marshal(), ensure_ascii=False) data = cbor2.dumps(user.marshal()) RESULT['objects'] += 1 RESULT['bytes'] += len(data)
def serialize(self, obj) -> bytes: return cbor2.dumps(obj, **self.encoder_options)
def _serialize_value(self, value): return cbor2.dumps(value)