def test_object(): signer = Signer(b'secret') obj = dict(key=1, value='value') dumped = signer.sign_json(obj) obj = signer.verify_json(dumped) assert obj['key'] == 1 assert obj['value'] == 'value'
def test_record(): signer = Signer(b'secret') l = ('1', 'value') dumped = signer.sign_record(l) k1, k2 = signer.verify_record(dumped) assert k1 == '1' assert k2 == 'value'
def test_expires(): signer = Signer(b'secret') l = ('2', 'value') tomorrow = datetime.utcnow() + timedelta(days=1) dumped = signer.sign_record(l, expires=tomorrow) k1, k2 = signer.verify_record(dumped) assert k1 == '2' assert k2 == 'value' yesterday = datetime.utcnow() + timedelta(days=-1) dumped = signer.sign_record(l, expires=yesterday) assert None is signer.verify_record(dumped)
def __init__(self, config, timeout=30, verify=False, **kwargs): ''' @config: the unionpay config object @timeout: request timeout seconds @verify: should verify ssl certification pem ''' self.config = config self.timeout = timeout self.verify = verify self.signer = Signer.getSigner(config)
def post(self, addr, data, **kwargs): data.update(signature=urlencode({'signature': data['signature']})[10:]) request_data = Signer.simple_urlencode(data) print(request_data) response = requests.post( addr, data=request_data, timeout=self.timeout, verify=self.verify, headers={'content-type': 'application/x-www-form-urlencoded'} ) if response.status_code != requests.codes.ok: msg = "[UPACP]request error: %s, reason: %s" \ % (response.status_code, response.reason) raise error.UnionpayError(msg) return response.content
def resign(input_path, certificate, key, apple_cert, provisioning_profile, output_path, info_props=None, alternate_entitlements_path=None): """ Unified interface to extract any kind of archive from a temporary file, resign it with these credentials, and create a similar archive for that resigned app """ if not exists(input_path): raise IOError("{0} not found".format(input_path)) log.debug('Signing with apple_cert: {}'.format(apple_cert)) log.debug('Signing with key: {}'.format(key)) log.debug('Signing with certificate: {}'.format(certificate)) log.debug( 'Signing with provisioning_profile: {}'.format(provisioning_profile)) signer = Signer(signer_cert_file=certificate, signer_key_file=key, apple_cert_file=apple_cert) ua = None bundle_info = None try: archive = archive_factory(input_path) if archive is None: raise NotSignable('No matching archive type found') ua = archive.unarchive_to_temp() if info_props: # Override info.plist props of the parent bundle ua.bundle.update_info_props(info_props) ua.bundle.resign(signer, provisioning_profile, alternate_entitlements_path) bundle_info = ua.bundle.info ua.archive(output_path) except NotSignable as e: msg = "Not signable: <{0}>: {1}\n".format(input_path, e) log.info(msg) raise finally: if ua is not None: ua.remove() return bundle_info
def __init__(self, credentials, region, service, action, api_version, enable_high_resolution_metrics=False): self.credentials = credentials self.region = region self.datestamp = None self.service = service self.action = action self.api_version = api_version self.aws_timestamp = None self.payload = "" # for HTTP GET payload is always empty self.querystring_builder = QuerystringBuilder( enable_high_resolution_metrics) self.signer = Signer(credentials, region, self.service, self._ALGORITHM)
def resign(input_path, certificate, key, apple_cert, provisioning_profile, output_path, info_props=None): """ Unified interface to extract any kind of archive from a temporary file, resign it with these credentials, and create a similar archive for that resigned app """ if not exists(input_path): raise IOError("{0} not found".format(input_path)) signer = Signer(signer_cert_file=certificate, signer_key_file=key, apple_cert_file=apple_cert) temp_dir = None try: archive = archive_factory(input_path) (temp_dir, bundle) = archive.unarchive_to_temp() if info_props: # Override info.plist props of the parent bundle bundle.update_info_props(info_props) newBundleID = dict( CFBundleIdentifier=getNewAppIDFromProfileEntitlements( provisioning_profile)) bundle.update_info_props(newBundleID) process_watchkit(bundle.path, REMOVE_WATCHKIT) bundle.resign(signer, provisioning_profile) archive.__class__.archive(temp_dir, output_path) except NotSignable as e: msg = "Not signable: <{0}>: {1}\n".format(input_path, e) log.info(msg) raise finally: if temp_dir is not None and isdir(temp_dir): shutil.rmtree(temp_dir)
def test_sha1(): signer = Signer(b'secret key', method='sha1', digest_size=20) tomorrow = datetime.utcnow() + timedelta(days=1) signed = signer.sign(b'message', expires=tomorrow) assert b'message' == signer.verify(signed)
def test_bad_signature(): signer = Signer(b'secret') raw = urlsafe_b64encode(b'data').decode() assert None is signer.verify_record(raw)
def test_bad_base64(): signer = Signer(b'secret') raw = 'asdf' assert None is signer.verify_record(raw)
def test_verify_signature(): signer = Signer(b'secret', 'sha1') msg = b'some msg' sig = signer.get_signature(msg) assert len(sig) assert signer.verify_signature(msg, sig)
def test_str(): signer = Signer(b'secret') msg = "message" signed = signer.sign_str(msg) assert msg == signer.verify_str(signed)
def setUpClass(cls): cls.signer = Signer(TEST_CUSTOMER)
def test_sign(): signer = Signer(b'secret') msg = b'some msg' dumped = signer.sign(msg) assert signer.verify(dumped) == msg
class Controller(): def __init__(self): self.running = False def handle(self, msg): info('controller', 'handle: '+str(msg)) try: name = msg.get_name() unit = msg.get_unit() if not name or not unit: return info('controller', 'name: '+name+', unit: '+unit) topic = msg.get_topic() if name == 'CONNECT' and unit == 'Requested' and msg.get_bool(): self.signPipe.send(('CONNECT', topic, msg.get_bool())) elif name == 'REGISTER' and unit == 'Pub_Key': self.signPipe.send(('REGISTER', topic, msg.get_str())) elif not name in ['CONNECT', 'CONNECTED', 'REGISTER', 'REGISTERED', 'TX']: self.signPipe.send(('TX', topic, msg.payload)) #################### Modify here to customize ######################## """ elif name == 'CustomCommand' and unit 'Custom' and msg.get_str(): #alter msg to use case msg = self.customMethod() #send msg to device publish(msg) """ ###################################################################### except Exception as ex: error('controller', 'handle error: '+str(ex)) def handle_admin(self, data): info('controller', 'handle admin: '+str(data)) try: msg = self.signer.decrypt(data) if not msg: return name = msg.get_name() unit = msg.get_unit() if not name or not unit or name != 'Admin' or unit != 'CMD': return info('controller', 'name: '+name+', unit: '+unit) vs = msg.get_str() if vs == 'Merge': self.signPipe.send(('Merge', 'KIT', vs)) elif vs == 'Status': self.signPipe.send(('Status', 'KIT', vs)) elif vs == 'Password': payload = msg.get_payload() self.signPipe.send(('Password', 'KIT', payload[1]['vs'])) elif vs == 'Test' or vs.startswith('Test_'): self.signPipe.send(('Test', 'KIT', msg.get_payload())) elif vs == 'Transfer': self.signPipe.send(('Transfer', 'KIT', msg.get_payload())) except Exception as ex: error('controller', 'handle admin error: '+str(ex)) def setup(self, pw = None): info('controller', 'setup') self.receiver = Receiver() self.sender = Sender() self.signer = Signer(pw) info('controller', 'sender process') self.sendPipe, sendPipe = mp.Pipe() self.senderProcess = mp.Process(target=self.sender.start, name='sender', args=(sendPipe,)) info('controller', 'signer process') self.signPipe, signPipe = mp.Pipe() self.signerProcess = mp.Process(target=self.signer.start, name='signer', args=(signPipe,)) info('controller', 'receiver process') self.receivePipe, receivePipe = mp.Pipe() self.receiverProcess = mp.Process(target=self.receiver.start, name='receiver', args=(receivePipe,)) def start(self): info('controller', 'start') try: self.senderProcess.start() self.signerProcess.start() self.receiverProcess.start() except Exception as ex: error('controller', 'start error: '+str(ex)) self.senderProcess.terminate() self.signerProcess.terminate() self.receiverProcess.terminate() self.senderProcess.join() self.signerProcess.join() self.receiverProcess.join() return else: self.running = True # Wait for the processes to start. time.sleep(3) # Subscribe to admin and sensor data. info('controller', 'subscribe to admin and sensor data') subscribe(self.handle_admin, channel='admin') subscribe(self.handle, channel='sensor') # Start processing messages. info('controller', 'processing messages!') while self.running: # Check to make sure the signer is not finished with a return # message for the broker. if self.signPipe.poll(): msg = self.signPipe.recv() info('controller', 'signer data: '+str(msg)) # Send message if not a Kit message, those go to admin. if msg.get_topic() != 'KIT': self.sendPipe.send(msg) # Handle Kit messages by sending to admin after encryption. else: info('controller', 'admin message: '+str(msg)) data = self.signer.encrypt(msg) info('controller', 'admin message: '+str(data)) publish_raw(data, channel='admin') # Check if the reciever has any data waiting and process. if self.receivePipe.poll(): msg = self.receivePipe.recv() info('controller', 'receiver data: '+str(msg)) self.handle(msg) get_message() time.sleep(0.001) def stop(self): info('controller', 'stop') self.running = False info('controller', 'stopping modules') self.receiver.stop() self.sender.stop() self.signer.stop() info('controller', 'terminating processes') self.receiverProcess.terminate() self.senderProcess.terminate() self.signerProcess.terminate() info('controller', 'unsubscribe from sensor data') unsubscribe()
import rtxp.core.address import rtxp.core.amount import rtxp.core.deserialize import rtxp.core.serialize from signer import Signer import traits address = rtxp.core.address.Address(traits.ALPHABET) Amount = rtxp.core.amount.create_amount(traits.NATIVE) deserializer = rtxp.core.deserialize.Deserializer(traits.NATIVE, address.account_to_human) serializer = rtxp.core.serialize.Serializer(traits.NATIVE, address.account_from_human) signer = Signer(address, serializer)
def get_signer(self, config): return Signer.getSigner(config)
class RequestBuilder(object): """ The request builder is responsible for building the PutMetricData requests using HTTP GET. Keyword arguments: credentials -- The AWSCredentials object containing access and secret keys region -- The region to which the data should be published namespace -- The namespace used for grouping of the published metrics. """ _SERVICE = "monitoring" _ACTION = "PutMetricData" _API_VERSION = "2010-08-01" _ALGORITHM = "AWS4-HMAC-SHA256" _V4_TERMINATOR = "aws4_request" def __init__(self, credentials, region): self.credentials = credentials self.region = region self.namespace = "" self.datestamp = None self.aws_timestamp = None self.payload = "" # for HTTP GET payload is always empty self.querystring_builder = QuerystringBuilder() self.signer = Signer(credentials, region, self._SERVICE, self._ALGORITHM) def create_signed_request(self, namespace, metric_list): """ Creates a ready to send request with metrics from the metric list passed as parameter """ self.namespace = namespace self._init_timestamps() canonical_querystring = self._create_canonical_querystring(metric_list) signature = self.signer.create_request_signature( canonical_querystring, self._get_credential_scope(), self.aws_timestamp, self.datestamp, self._get_canonical_headers(), self._get_signed_headers(), self.payload) canonical_querystring += '&X-Amz-Signature=' + signature return canonical_querystring def _init_timestamps(self): """ Initializes timestamp and datestamp values """ self.datestamp = get_datestamp() self.aws_timestamp = get_aws_timestamp() def _create_canonical_querystring(self, metric_list): """ Creates a canonical querystring as defined in the official AWS API documentation: http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html """ return self.querystring_builder.build_querystring( metric_list, self._get_request_map()) def _get_request_map(self): """ Creates a map of request parameters and values which can be used to build a canonical querystring """ canonical_map = { "Action": self._ACTION, "Namespace": self.namespace, "Version": self._API_VERSION, "X-Amz-Algorithm": self._ALGORITHM, "X-Amz-Credential": self.credentials.access_key + '/' + self._get_credential_scope(), "X-Amz-Date": self.aws_timestamp, "X-Amz-SignedHeaders": self._get_signed_headers() } if self.credentials.token: canonical_map["X-Amz-Security-Token"] = self.credentials.token return canonical_map def _get_credential_scope(self): """ Builds credential scope string used in querystring and signing """ return self.datestamp + '/' + self.region + '/' + self._SERVICE + '/' + self._V4_TERMINATOR def _get_canonical_headers(self): """ Returns a list of canonical headers separated with new line characters """ return "host:" + self._get_host() + "\n" def _get_signed_headers(self): """ Returns comma delimited list of signed headers """ return "host" def _get_host(self): """ Returns the endpoint's hostname derived from the region """ if self.region == "localhost": return "localhost" elif self.region.startswith("cn-"): return "monitoring." + self.region + ".amazonaws.com.cn" return "monitoring." + self.region + ".amazonaws.com"
def setUpClass(cls): cls.signer = Signer(TEST_CUSTOMER) cls.signer.generate_certificates()