Ejemplo n.º 1
0
class CDMAClient(Client):
    """ A CDMA client """
    handlers = []
    chip = ''

    def __init__(self, name, host = 'localhost', port = 10000):
        Client.__init__(self, host, port)
        self.name = name
        self.crypt = Crypt()
        self.handlers = [self.socket, sys.stdin]

    def run(self):
        self.send(sys.argv[1])
        self.chip = self.socket.recv(1024)
        if self.chip == 'NNNN':
            raise ValueError()
        else:
            print 'client ' + self.name + ' got chip ' + self.chip

        while True:
            readable, writeable, ex = select.select(self.handlers, [], [])
            for r in readable:
                if r == sys.stdin:
                    input = raw_input().split(' ')
                    self.socket.send(input[0])
                    addresseeChip = self.socket.recv(1024)
                    self.socket.send(self.crypt.encrypt(addresseeChip, input[1]))
                else:
                    data = r.recv(1024)
                    print 'received: ' + self.crypt.decrypt(self.chip, data)
Ejemplo n.º 2
0
def write_config(config, config_file=""):
    if len(config) < 3:
        print("Error not enough config vars passed.")
        exit()
    if config_file == "":
        file = open("/home/pi/fireball_camera/config.txt", "w")
    else:
        file = open(config_file, "w")
    for key in config:
        if key == 'cam_pwd':
            try:
                #We ecrypt the cam password if it is not crypted
                c = Crypt()
                temp = c.decrypt(config['cam_pwd'])
            except:
                config['cam_pwd'] = c.encrypt(config['cam_pwd'])

        if key != 'IP':
            if key == 'cam_ip' and config[key] == '192.168.1.88':
                print("skip.")
            else:
                line = key + "=" + str(config[key]) + "\n"
                file.write(line)

    file.close()
    print("Config written.")
Ejemplo n.º 3
0
 def test_ed_cycle(self):
     
     for pt, pph in d_values:
         
         c = Crypt(pph)
         u = c.encrypt(pt)
         dc = c.decrypt(u)
         
         print "assert equal: %s == %s" % (dc, str(pt))
         self.assertEqual(dc, str(pt)) 
Ejemplo n.º 4
0
 def encrypt_text(self, gui, password_entry):
     textentry = self.get_current_textview(gui)
     password = password_entry.get_text()
     textbuffer = Gtk.TextBuffer()
     textbuffer = textentry.get_buffer()
     buffer_start = textbuffer.get_start_iter()
     buffer_end = textbuffer.get_end_iter()
     content = textbuffer.get_text(buffer_start, buffer_end, True)
     key = password
     Cipher = Crypt()
     content_crypted = Cipher.encrypt(key, content)
     try:
         textbuffer.set_text(content_crypted)
         textentry.set_buffer(textbuffer)
     except TypeError:
         print("Type Error")
Ejemplo n.º 5
0
def add_to_config(param,new_value):
    #Read Current Config
    
    if(param!='cam_pwd'):
    
        config = read_config_raw();
        
        logging.debug('Try to update the config file with ' +  str(param) + ' = ' + str(new_value))
        
        updated = 0;
        
        #Loop throught config
        for key in config:
            
            if(key == param):
                config[key] = new_value
                updated = 1;
        
        # In case the param doesnt exist yet in the config file
        if(updated==0):
            config[param] = new_value
            logging.debug('The parameter ' + str(param) + ' didnt exist in config.txt')
            
        # We rewrite the config file
        # WARNING: we need to recrypt cam_pwd here as read_config_raw decrypt it   
        
        file = open("/home/pi/fireball_camera/config.txt", "w")
        
        for key in config:
            value = config[key]
            
            if(key=='cam_pwd'):
                c     = Crypt()
                value = c.encrypt(value)

            if(key!='error'):    
                line = str(key) + "=" + str(value) + "\n"
                file.write(line) 
                   
        file.close()
        
    else:
        logging.error('We tried to update cam_pwd with add_to_config: IMPOSSIBLE')
Ejemplo n.º 6
0
def remove_from_config(param):
    
    config = read_config_raw(); 
    i=0

    while i < len(param):
      if(param[i] in config):
        del config[param[i]]
      i += 1  
 
    file = open("/home/pi/fireball_camera/config.txt", "w")
    for key in config:
        value = config[key]
            
        if(key=='cam_pwd'):
            c     = Crypt()
            value = c.encrypt(value)
            
        line = str(key) + "=" + str(value) + "\n"
        file.write(line) 
                   
    file.close()
Ejemplo n.º 7
0
    print('\n')
    print(Fore.YELLOW + '!' + Style.RESET_ALL)
    print(
        Fore.YELLOW +
        'Não se preocupe, não enviaremos essa informação para nenhum local, apenas será encriptada na sua máquina como cache.'
        + Style.RESET_ALL)
    print(Fore.YELLOW + '!' + Style.RESET_ALL)
    print('\n')

    key_file = open('key.key', 'rb')
    key = key_file.read()
    key_file.close()

    if not key:
        c.generate_new_key()
        c.encrypt(bearer_token)
    else:
        c.encrypt(bearer_token)

    encrypted_token_file = open('token.txt', 'rb')
    encrypted_token = encrypted_token_file.read()
    encrypted_token_file.close()

    if not encrypted_token:
        print(f'{Fore.RED}Ocorreu um erro, tente novamente{Style.RESET_ALL}')

    original_token = c.decrypt(encrypted_token)
else:
    try:
        original_token = c.decrypt(encrypted_token)
    except Exception as err:
Ejemplo n.º 8
0
def get_assignments():

    print(ascii_art.return_ascii())

    print('Tentando encontrar o Bearer token...\n')

    c = Crypt()

    encrypted_token_file = open('token.txt', 'rb')
    encrypted_token = encrypted_token_file.read()
    encrypted_token_file.close()

    if not encrypted_token:
        print(
            f'{Fore.YELLOW}Não conseguimos localizar seu token salvo em cache, digite manualmente{Style.RESET_ALL}'
        )
        print('Digite o seu bearer token do Teams: ')
        bearer_token = str(input('')).strip()

        print('\n')
        print(Fore.YELLOW + '!' + Style.RESET_ALL)
        print(
            Fore.YELLOW +
            'Não se preocupe, não enviaremos essa informação para nenhum local, apenas será encriptada na sua máquina como cache.'
            + Style.RESET_ALL)
        print(Fore.YELLOW + '!' + Style.RESET_ALL)
        print('\n')

        key_file = open('key.key', 'rb')
        key = key_file.read()
        key_file.close()

        if not key:
            c.generate_new_key()
            c.encrypt(bearer_token)
        else:
            c.encrypt(bearer_token)

        encrypted_token_file = open('token.txt', 'rb')
        encrypted_token = encrypted_token_file.read()
        encrypted_token_file.close()

        if not encrypted_token:
            print(
                f'{Fore.RED}Ocorreu um erro, tente novamente{Style.RESET_ALL}')

        original_token = c.decrypt(encrypted_token)
    else:
        try:
            original_token = c.decrypt(encrypted_token)
        except Exception as err:
            print(f'{Fore.RED}{err}{Style.RESET_ALL}')
            clear_token()
            exit()

        print(
            f'{Fore.BLUE}Seu token foi encontrado em cache!{Style.RESET_ALL}\n'
        )

    print('Pegando assignments... (Isso pode demorar alguns minutos)\n')

    ts = TeamScrap(original_token)

    try:
        classes_assignments = ts.get_all_classes_assignments()
    except Exception as err:
        print(f'{Fore.RED}{err}{Style.RESET_ALL}\n')
        print(
            f'{Fore.RED}Verifique se o token não expirou ou está correto{Style.RESET_ALL}\n'
        )
        clear_token()
        exit()

    overdue_assignments = 0

    print('=' * 100)
    message = ""
    for class_assignment in classes_assignments:
        created_date_time = class_assignment['assignmentInfo'][
            'createdDateTime']
        [created_date_parsed,
         created_hours_parsed] = parse_teams_date_time(created_date_time)
        created_date_final = datetime(year=int(created_date_parsed[0]),
                                      month=int(created_date_parsed[1]),
                                      day=int(created_date_parsed[2]))
        bimester_init_date = datetime(year=int(2021), month=int(2), day=int(1))

        if created_date_final > bimester_init_date:
            due_date_time = class_assignment['assignmentInfo']['dueDateTime']
            [date_parsed, hours_parsed] = parse_teams_date_time(due_date_time)

            date_init = datetime.now()
            date_final = datetime(year=int(date_parsed[0]),
                                  month=int(date_parsed[1]),
                                  day=int(date_parsed[2]),
                                  hour=int(hours_parsed[0]),
                                  minute=int(hours_parsed[1]),
                                  second=int(hours_parsed[2]))

            date_final -= timedelta(hours=3)

            [final_date_parsed,
             final_hours_parsed] = parse_date_time(date_final)

            remaining_date = date_final - date_init

            remaining_date_parsed = str(remaining_date).split(',')

            message += f"""\n\n📝 Tarefa: {class_assignment['assignmentInfo']['displayName']}
						\n📚 Disciplina: {class_assignment["classInfo"][0]["name"]}
						\n⏳ Data de entrega: {final_date_parsed[2]}/{final_date_parsed[1]}/{final_date_parsed[0]}
						às {final_hours_parsed[0]}:{final_hours_parsed[1]}:{final_hours_parsed[2]}"""

            if class_assignment['assignmentInfo'][
                    'allowLateSubmissions'] == 'true':
                message += "\n⏰ Aceita atrasos: ✅SIM✅"
            else:
                message += "\n⏰ Aceita atrasos: ❌NÃO❌"

            if len(remaining_date_parsed) > 1:
                remaining_days = int(
                    remaining_date_parsed[0].strip().split(' ')[0])
                remaining_hours = remaining_date_parsed[1].strip().split(':')
            else:
                remaining_hours = remaining_date_parsed[0].strip().split(':')

            if int(remaining_days) < 0:
                message += "\n⚙️ Status: ⌛️VENCIDA⌛️"
            else:
                message += "\n⚙️ Status: 🏃CORRE QUE DÁ TEMPO🏃"

            message += "\n" + "=" * 10
        else:
            pass

    return message
Ejemplo n.º 9
0
        else:
        
            logging.debug('cam_pwd does NOT exist in config.txt - we add it')
             
            #Update the Cam Password via the cgi
            fname = 'http://'+config['cam_ip']+'/cgi-bin/pwdgrp_cgi?action=update&user=admin&pwd=admin&username=admin&password='******'Updating the cam_pwd on the camera side:' + fname)

         
        # Call to CGI
        urllib.urlopen(fname)
         
        # Encrypt the Cam Password to store it in the config file 
        try:
            c     = Crypt()
            value = c.encrypt(value)
            logging.debug('cam_pwd successfully encrypted') 
            
            # Write new pwd in config.txt
            line = "cam_pwd=" + str(value) + "\n"
            file.write(line)   
        except:
            logging.error('IMPOSSIBLE to encrypted the following cam_pwd ' + str(value))
            logging.debug('Config (ERROR) ' + str(config))
        
        del tmp_config['new_cam_pwd']


logging.debug('Updating config.txt') 
for key in tmp_config:
    value = tmp_config[key]
Ejemplo n.º 10
0
class Backup:
	"""Handles complete backup flow. Check if file exists orhas been modified.
	Compresses, encrypts and uploads the file to th destination."""

	db = None
	job = None
	compress = None
	encrypt = None
	
	def __init__(self, job, db):
		self.job = job
		self.db = db
		
		self.archive = Archive()
		self.crypt = Crypt()
	
	def backup(self):
		"""Start backup process."""
		
		if not isdir(self.job['path']):
			self._list_files(
				None, dirname(self.job['path']), [basename(self.job['path']), ]
			)
		else:
			walk(self.job['path'], self._list_files, None)
		
	def _list_files(self, dir, basepath, files):
		"""Callback for walker. Iterates over filelist, builds absolute path
		and checks wheather to skip or upload the file."""
		
		for file in files:
			# absolute path
			path = join(basepath, file)
			
			# only work on files
			if isfile(path)	or (
				not isdir(path) and self.job.has_key('pre_command')):
				
				item = self.db.get_file(self.job['name'], path)
				
				# file is not in db
				if not item:
					self._backup_file(path)
				else:
					# file exists in db, but has a different mtime
					if isfile(path):
						mtime = getmtime(path)
						
						if int(item['mtime']) != int(mtime):
							self._backup_file(path)
					else:
						self._backup_file(path)
						
	def _execute_command(self, command):
		"""Execute pre- or postcommand."""
		if self.job.has_key(command):
			try:
				logging.info('[%s] Executing %s' 
					% (self.job['name'], self.job[command]))
				system(self.job[command])
			except:
				logging.warn('[%s] Command failed %s' 
					% (self.job['name'], self.job[command]))

	def _backup_file(self, path):
		"""Back ups specific file to desired storage device."""
		
		print('[%s] Starting backup for %s' % (self.job['name'], path))
		
		# precommand
		self._execute_command('pre_command')
		
		# get size, mtime
		file_info = self._file_info(path)
		
		# get storeage wrapper
		storage = self._get_account(self.job['destination'])
		dest = join(tempfile.gettempdir(), 'umaticssync')
		
		# is compression deired? bzip2 file
		if self.job.has_key('compress') and self.job['compress'] == 'true':
			logging.info('[%s] Compressing %s' % (self.job['name'], path))
			self.archive.compress(path, dest)
			old_dest = dest
			compressed = 1
		
		# is encryption desired? encrypt with user id
		if self.job.has_key('encrypt') and self.job['encrypt']:
			logging.info('[%s] Encrypting %s' % (self.job['name'], path))
			self.crypt.encrypt(self.job['encrypt'], dest)
			dest = dest + '.gpg'
			remove(old_dest)
			encrypted = 1
		
		# add file/increase revision
		info = self.db.add_file(
			self.job['name'], path, file_info['mtime'], file_info['size'], 
			encrypted, compressed)
		
		# build key and upload, cleanup
		key = normpath('%s/%s.r%%s' % (self.job['name'], path))
		logging.info('[%s] Uploading %s.r%s' 
			% (self.job['name'], path, info['revision']))
		storage.store_file(key % info['revision'], dest)
		remove(dest)
		
		# cleanup old revisions
		revision = int(info['revision']) - int(self.job['revisions'])
		if revision >= 0:
			print "del", key % revision
			storage.del_file(key % revision)
			
		# postcommand
		self._execute_command('post_command')
		
	def _file_info(self, path):
		"""Returns size and mtime."""
		return {'size': getsize(path), 'mtime': getmtime(path)}
		
	def _get_account(self, uri):
		"""Return storage engine object based on the provided URI string."""
		uri = urlsplit(uri)
		
		# s3 backend
		if uri[0] == 's3':
			a_key, s_key = uri[2][2:].split('@')[0].split(':')
			bucket = uri[2][2:].split('@')[1]
			
			from wrapper.S3Wrapper import S3Wrapper
			return S3Wrapper(a_key, s_key, bucket)
		# ftp server
		elif uri[0] == 'ftp':
			user, passwd = uri[2][2:].split('@')[0].split(':')
			host = uri[2][2:].split('@')[1]
			path = uri[2]
			
			from wrapper.FTPWrapper import FTPWrapper
			return FTPWrapper(host, user, passwd, path)
		# @todo: implement
		elif uri[0] == 'scp':
			pass
		# local storage backend
		elif uri[0] == 'file':
			path = uri[1]
			
			from wrapper.FileWrapper import FileWrapper
			return FileWrapper(path)

	def restore(self, revision):
		files = self.db.get_files(self.job['name'])
		
		if len(files) == 0:
			#logging.info('[%s] No files found for backup job')
			return False
		
		# get storage instance
		storage = self._get_account(self.job['destination'])
		
		# iterate thur files
		for file in files:
			try:
				# is given revision in allowed range?
				rev_diff = int(file['revision']) - int(self.job['revisions'])
				if int(revision) in range(rev_diff, file['revision'] + 1):
					rev = revision
				else:
					# fallback to latest file revision
					rev = file['revision']
			except:
				rev = file['revision']
			
			logging.info('[%s] Restoring %s.r%s' 
				% (self.job['name'], file['path'], rev))
			
			# get file
			key = normpath('%s/%s.r%s' % (self.job['name'], file['path'], rev))
			dest = join(tempfile.gettempdir(), 'umaticssync')
			
			logging.info('[%s] Downloading %s' 
				% (self.job['name'], file['path']))
			storage.get_file(key, dest)
			
			if file['encrypted'] == 1:
				logging.info('[%s] Decrypting %s' 
					% (self.job['name'], file['path']))
				self.crypt.decrypt(self.job['encrypt'], dest, dest)
			
			if file['compressed'] == 1:
				logging.info('[%S] Extracting %s' 
					% (self.job['name'], file['path']))
				self.archive.extract(dest)
			else:
				rename(dest, file['path'])
Ejemplo n.º 11
0
class TransactionFactory(object):
    def __init__(self,
                 config,
                 mongo,
                 block_height,
                 bulletin_secret='',
                 username='',
                 value=0,
                 fee=0.0,
                 requester_rid='',
                 requested_rid='',
                 public_key='',
                 dh_public_key='',
                 private_key='',
                 dh_private_key='',
                 to='',
                 inputs='',
                 outputs='',
                 coinbase=False,
                 chattext=None,
                 signin=None):
        self.config = config
        self.mongo = mongo
        self.block_height = block_height
        self.bulletin_secret = bulletin_secret
        self.username = username
        self.requester_rid = requester_rid
        self.requested_rid = requested_rid
        self.public_key = public_key
        self.dh_public_key = dh_public_key
        self.private_key = private_key
        self.value = value
        self.fee = float(fee)
        self.dh_private_key = dh_private_key
        self.to = to
        self.time = str(int(time.time()))
        self.outputs = []
        for x in outputs:
            self.outputs.append(Output.from_dict(x))
        self.inputs = []
        for x in inputs:
            if 'signature' in x:
                self.inputs.append(
                    ExternalInput.from_dict(self.config, self.mongo, x))
            else:
                self.inputs.append(Input.from_dict(x))
        self.coinbase = coinbase
        self.chattext = chattext
        self.signin = signin
        self.do_money()
        inputs_concat = self.get_input_hashes()
        outputs_concat = self.get_output_hashes()
        if bulletin_secret:
            self.rid = self.generate_rid()
            if self.chattext:
                self.relationship = json.dumps({"chatText": self.chattext})
                self.cipher = Crypt(self.config.wif)
                self.encrypted_relationship = self.cipher.encrypt(
                    self.relationship)
            elif self.signin:
                for shared_secret in TU.get_shared_secrets_by_rid(
                        self.config, self.mongo, self.rid):
                    self.relationship = SignIn(self.signin)
                    self.cipher = Crypt(shared_secret.encode('hex'),
                                        shared=True)
                    self.encrypted_relationship = self.cipher.shared_encrypt(
                        self.relationship.to_json())
            else:
                if not self.dh_public_key or not self.dh_private_key:
                    a = os.urandom(32)
                    self.dh_public_key = scalarmult_base(a).encode('hex')
                    self.dh_private_key = a.encode('hex')
                self.relationship = self.generate_relationship()
                if not private_key:
                    raise BaseException('missing private key')
                self.cipher = Crypt(self.config.wif)
                self.encrypted_relationship = self.cipher.encrypt(
                    self.relationship.to_json())
        else:
            self.rid = ''
            self.encrypted_relationship = ''

        self.header = (self.public_key + self.time + self.dh_public_key +
                       self.rid + self.encrypted_relationship +
                       "{0:.8f}".format(self.fee) + self.requester_rid +
                       self.requested_rid + inputs_concat + outputs_concat)
        self.hash = hashlib.sha256(self.header).digest().encode('hex')
        if self.private_key:
            self.transaction_signature = TU.generate_signature_with_private_key(
                private_key, self.hash)
        else:
            self.transaction_signature = ''
        self.transaction = self.generate_transaction()

    def do_money(self):
        my_address = str(
            P2PKHBitcoinAddress.from_pubkey(self.public_key.decode('hex')))
        input_txns = BU.get_wallet_unspent_transactions(
            self.config, self.mongo, my_address)
        miner_transactions = self.mongo.db.miner_transactions.find()
        mtxn_ids = []
        for mtxn in miner_transactions:
            for mtxninput in mtxn['inputs']:
                mtxn_ids.append(mtxninput['id'])

        if self.inputs:
            inputs = self.inputs
        else:
            inputs = []
            for input_txn in input_txns:
                if input_txn['id'] not in mtxn_ids:
                    if 'signature' in input_txn:
                        inputs.append(
                            ExternalInput.from_dict(self.config, self.mongo,
                                                    input_txn))
                    else:
                        inputs.append(Input.from_dict(input_txn))

        input_sum = 0
        if self.coinbase:
            self.inputs = []
        else:
            if inputs:
                needed_inputs = []
                done = False
                for y in inputs:
                    print y.id
                    txn = BU.get_transaction_by_id(self.config,
                                                   self.mongo,
                                                   y.id,
                                                   instance=True)
                    if isinstance(y, ExternalInput):
                        y.verify()
                        address = str(
                            P2PKHBitcoinAddress.from_pubkey(
                                txn.public_key.decode('hex')))
                    else:
                        address = my_address
                    for txn_output in txn.outputs:
                        if txn_output.to == address:
                            input_sum += txn_output.value
                            needed_inputs.append(y)
                            if input_sum >= (
                                    sum([x.value
                                         for x in self.outputs]) + self.fee):
                                done = True
                                break
                    if done == True:
                        break

                if not done:
                    raise NotEnoughMoneyException('not enough money')
                self.inputs = needed_inputs
            else:
                self.inputs = []

            remainder = input_sum - (sum([x.value
                                          for x in self.outputs]) + self.fee)

            found = False
            for x in self.outputs:
                if my_address == x.to:
                    found = True
                    x.value += remainder
            if not found:
                return_change_output = Output(to=my_address, value=remainder)
                self.outputs.append(return_change_output)

    def get_input_hashes(self):
        from fastgraph import FastGraph
        input_hashes = []
        for x in self.inputs:
            txn = BU.get_transaction_by_id(self.config,
                                           self.mongo,
                                           x.id,
                                           instance=True,
                                           include_fastgraph=isinstance(
                                               self, FastGraph))
            input_hashes.append(str(txn.transaction_signature))

        return ''.join(sorted(input_hashes, key=str.lower))

    def get_output_hashes(self):
        outputs_sorted = sorted([x.to_dict() for x in self.outputs],
                                key=lambda x: x['to'].lower())
        return ''.join(
            [x['to'] + "{0:.8f}".format(x['value']) for x in outputs_sorted])

    def generate_rid(self):
        my_bulletin_secret = self.config.get_bulletin_secret()
        if my_bulletin_secret == self.bulletin_secret:
            raise BaseException(
                'bulletin secrets are identical. do you love yourself so much that you want a relationship on the blockchain?'
            )
        bulletin_secrets = sorted(
            [str(my_bulletin_secret),
             str(self.bulletin_secret)],
            key=str.lower)
        return hashlib.sha256(
            str(bulletin_secrets[0]) +
            str(bulletin_secrets[1])).digest().encode('hex')

    def generate_relationship(self):
        return Relationship(
            dh_private_key=self.dh_private_key,
            their_bulletin_secret=self.bulletin_secret,
            their_username=self.username,
            my_bulletin_secret=self.config.get_bulletin_secret(),
            my_username=self.config.username)

    def generate_transaction(self):
        return Transaction(self.config,
                           self.mongo,
                           self.block_height,
                           self.time,
                           self.rid,
                           self.transaction_signature,
                           self.encrypted_relationship,
                           self.public_key,
                           self.dh_public_key,
                           float(self.fee),
                           self.requester_rid,
                           self.requested_rid,
                           self.hash,
                           inputs=[x.to_dict() for x in self.inputs],
                           outputs=[x.to_dict() for x in self.outputs],
                           coinbase=self.coinbase)

    def generate_transaction_signature(self):
        return TU.generate_signature(self.hash, self.private_key)
Ejemplo n.º 12
0
                    # Parse command from standard input
                    try:
                        reply = sys.stdin.readline()
                    except:
                        pass

                    if reply == 'exit\n':
                        return

                # Set sequence number and identifier
                icmp.set_icmp_id(icmp_id)
                icmp.set_icmp_seq(seq_id)

                # Include the command as data inside the ICMP packet
                reply = reply.encode('utf8')
                data = encryptor.encrypt(reply)
                icmp.contains(ImpactPacket.Data(data))

                # Calculate its checksum
                icmp.set_icmp_cksum(0)
                icmp.auto_checksum = 1

                # Have the IP packet contain the ICMP packet (along with its payload)
                ip.set_ip_src(client)
                ip.set_ip_dst(server)
                ip.contains(icmp)

                # Send it to the target host
                sock.sendto(ip.get_packet(), (server, 0))

if __name__ == '__main__':
class TransactionFactory(object):
    def __init__(self,
                 bulletin_secret='',
                 username='',
                 value=0,
                 fee=0.0,
                 requester_rid='',
                 requested_rid='',
                 public_key='',
                 dh_public_key='',
                 private_key='',
                 dh_private_key='',
                 to='',
                 inputs='',
                 outputs='',
                 coinbase=False,
                 chattext=None,
                 signin=None):
        self.bulletin_secret = bulletin_secret
        self.username = username
        self.requester_rid = requester_rid
        self.requested_rid = requested_rid
        self.public_key = public_key
        self.dh_public_key = dh_public_key
        self.private_key = private_key
        self.value = value
        self.fee = float(fee)
        self.dh_private_key = dh_private_key
        self.to = to
        self.outputs = outputs or []
        self.inputs = inputs
        self.coinbase = coinbase
        self.chattext = chattext
        self.signin = signin
        self.do_money()
        inputs_concat = self.get_input_hashes()
        outputs_concat = self.get_output_hashes()
        if bulletin_secret:
            self.rid = self.generate_rid()
            if self.chattext:
                self.relationship = json.dumps({"chatText": self.chattext})
            elif self.signin:
                for shared_secret in TU.get_shared_secrets_by_rid(self.rid):
                    self.relationship = SignIn(self.signin)
                    self.cipher = Crypt(shared_secret.encode('hex'),
                                        shared=True)
                    self.encrypted_relationship = self.cipher.shared_encrypt(
                        self.relationship.to_json())
            else:
                self.relationship = self.generate_relationship()
                if not private_key:
                    raise BaseException('missing private key')
                self.cipher = Crypt(Config.wif)
                self.encrypted_relationship = self.cipher.encrypt(
                    self.relationship.to_json())
        else:
            self.rid = ''
            self.encrypted_relationship = ''
        self.hash = hashlib.sha256(self.dh_public_key + self.rid +
                                   self.encrypted_relationship +
                                   "{0:.8f}".format(self.fee) +
                                   self.requester_rid + self.requested_rid +
                                   inputs_concat +
                                   outputs_concat).digest().encode('hex')

        self.transaction_signature = self.generate_transaction_signature()
        self.transaction = self.generate_transaction()

    def do_money(self):
        Mongo.init()
        my_address = str(
            P2PKHBitcoinAddress.from_pubkey(self.public_key.decode('hex')))
        input_txns = BU.get_wallet_unspent_transactions(my_address)
        miner_transactions = Mongo.db.miner_transactions.find()
        mtxn_ids = []
        for mtxn in miner_transactions:
            for mtxninput in mtxn['inputs']:
                mtxn_ids.append(mtxninput['id'])

        inputs = [
            Input.from_dict(input_txn) for input_txn in input_txns
            if input_txn['id'] not in mtxn_ids
        ]

        input_sum = 0
        if self.coinbase:
            self.inputs = []
        else:
            needed_inputs = []
            done = False
            for y in inputs:
                print y.id
                txn = BU.get_transaction_by_id(y.id, instance=True)
                for txn_output in txn.outputs:
                    if txn_output.to == my_address:
                        input_sum += txn_output.value
                        needed_inputs.append(y)
                        if input_sum >= (sum([x.value for x in self.outputs]) +
                                         self.fee):
                            done = True
                            break
                if done == True:
                    break

            if not done:
                raise NotEnoughMoneyException('not enough money')
            self.inputs = needed_inputs

            return_change_output = Output(
                to=my_address,
                value=input_sum - (sum([x.value
                                        for x in self.outputs]) + self.fee))
            self.outputs.append(return_change_output)

    def get_input_hashes(self):
        input_hashes = []
        for x in self.inputs:
            txn = BU.get_transaction_by_id(x.id, instance=True)
            input_hashes.append(str(txn.transaction_signature))

        return ''.join(sorted(input_hashes, key=str.lower))

    def get_output_hashes(self):
        outputs_sorted = sorted([x.to_dict() for x in self.outputs],
                                key=lambda x: x['to'].lower())
        return ''.join(
            [x['to'] + "{0:.8f}".format(x['value']) for x in outputs_sorted])

    def generate_rid(self):
        my_bulletin_secret = Config.get_bulletin_secret()
        if my_bulletin_secret == self.bulletin_secret:
            raise BaseException(
                'bulletin secrets are identical. do you love yourself so much that you want a relationship on the blockchain?'
            )
        bulletin_secrets = sorted(
            [str(my_bulletin_secret),
             str(self.bulletin_secret)],
            key=str.lower)
        return hashlib.sha256(
            str(bulletin_secrets[0]) +
            str(bulletin_secrets[1])).digest().encode('hex')

    def generate_relationship(self):
        return Relationship(dh_private_key=self.dh_private_key,
                            their_bulletin_secret=self.bulletin_secret,
                            their_username=self.username,
                            my_bulletin_secret=Config.get_bulletin_secret(),
                            my_username=Config.username)

    def generate_transaction(self):
        return Transaction(self.rid,
                           self.transaction_signature,
                           self.encrypted_relationship,
                           self.public_key,
                           self.dh_public_key,
                           float(self.fee),
                           self.requester_rid,
                           self.requested_rid,
                           self.hash,
                           inputs=self.inputs,
                           outputs=self.outputs,
                           coinbase=self.coinbase)

    def generate_transaction_signature(self):
        return TU.generate_signature(self.hash)
Ejemplo n.º 14
0
 def test_encrypt(self):
     c = Crypt(self.cipher_key)
     encrypted = c.encrypt('some random plain text')
     assert encrypted == 'b1XdLeAJ54bz/ALcDd2FeAez7y5z33Le'
Ejemplo n.º 15
0
class Api:
    """ Deal with API requests and local clipboard
    """

    SERVER = None
    USER = None
    HASH_LOGIN = None
    HASH_MSG = None
    crypto = None

    def __init__(self, server, user, hash_login, hash_msg):
        self.SERVER = server
        self.USER = user
        self.HASH_LOGIN = hash_login
        self.HASH_MSG = hash_msg
        self.crypto = Crypt(username=user,
                            password=None,
                            hash_login=hash_login,
                            hash_msg=hash_msg)

    def upload(self):
        """
        Send the copied text to SERVER
        """
        clip = self.copy()
        clip_encrypted = self.crypto.encrypt(clip)
        payload = {"text": clip_encrypted, "device": f"{Config.DEVICE_ID}"}
        try:
            res = requests.post(
                self.SERVER + Config.API_COPY_PASTE,
                data=payload,
                auth=(self.USER, self.HASH_LOGIN),
                timeout=Config.CONN_TIMEOUT,
                verify=Config.VERIFY_SSL_CERT,
                headers=Config.HEADERS,
            )
        except requests.exceptions.RequestException as e:
            log.exception("Error in upload request")
            raise ApiException(e)
        else:
            if res.status_code == 201:
                log.info("Success! Copied to Cloud-Clipboard.")
                return clip
            else:
                log.error(f"Error cannot upload clip: {res.text}")
                raise ApiException(res.text[0:Config.MAX_RESPONSE_LEN])

    def download(self):
        """
        Download last or all clips from SERVER and updates the local clipboard
        """
        log.info("downloading clips")
        url = self.SERVER + Config.API_COPY_PASTE
        try:
            res = requests.get(
                url=url,
                auth=(self.USER, self.HASH_LOGIN),
                timeout=Config.CONN_TIMEOUT,
                verify=Config.VERIFY_SSL_CERT,
                headers=Config.HEADERS,
            )
        except requests.exceptions.RequestException as e:
            log.exception("Error in download request")
            raise ApiException(e)
        else:
            if res.status_code == 200:
                clips_decrypted = self.parse_and_decrypt_response(res)
                log.info(f"Got new clips from SERVER:\n{clips_decrypted}")
                self.paste(clips_decrypted[-1])
                return clips_decrypted
            else:
                log.error(
                    f"Cannot download clips: {res.status_code} - {res.text}")
                raise ApiException(res.text[0:Config.MAX_RESPONSE_LEN])

    def parse_and_decrypt_response(self, response):
        """ Parse list clip response and decrypt content
        Returns:
            List: Contains one or more clips. Ordered by creation date (DESC)
        """
        clips_decrypted = []
        try:
            clips = json.loads(response.text)
            for clip in clips:
                clips_decrypted.append(self.crypto.decrypt(clip["text"]))
            if len(clips) == 0:
                clips_decrypted = ["There are no shared Clips yet"]
        except Exception as e:
            log.e(f"Could not parse and decrypt: {e}")
            clips_decrypted = [""]
        return clips_decrypted

    @staticmethod
    def paste(data):
        """
        Copies 'data' to local clipboard which enables pasting.
        """
        pyperclip.copy(data)

    @staticmethod
    def copy():
        """
        Return the current clipboard text
        """
        data = pyperclip.paste()
        return data

    @staticmethod
    def register(server, user, pw):
        """
        register user on server using hash generated from pw
        """
        crypto = Crypt(user, pw)
        login_hash = crypto.pw_hash_login
        payload = {"username": user, "password": login_hash}
        try:
            res = requests.post(
                server + Config.API_REGISTER,
                data=payload,
                timeout=Config.CONN_TIMEOUT,
                verify=Config.VERIFY_SSL_CERT,
                headers=Config.HEADERS,
            )
        except requests.exceptions.RequestException as e:
            log.exception("Error in register request")
            raise RegisterException(e)
        if res.status_code == 201:
            log.info(f"Hi {user}! You are all set.")
            return True
        else:
            log.error(f"Cannot register user: {res.status_code} - {res.text}")
            raise RegisterException(res.text[0:Config.MAX_RESPONSE_LEN])

    @staticmethod
    def login(server, user, pw):
        """
        authenticate user using hash generated from pw
        """
        crypto = Crypt(user, pw)
        login_hash = crypto.pw_hash_login
        try:
            res = requests.get(
                server + Config.API_LOGIN,
                auth=(user, login_hash),
                timeout=Config.CONN_TIMEOUT,
                verify=Config.VERIFY_SSL_CERT,
                headers=Config.HEADERS,
            )
        except requests.exceptions.RequestException as e:
            log.exception("Error in login request")
            raise LoginException(e)
        if res.status_code >= 200 and res.status_code < 400:
            log.info("Login successful")
            return True
        else:
            log.error(f"Login failed: {res.status_code} - {res.text}")
            raise LoginException(res.text[0:Config.MAX_RESPONSE_LEN])
Ejemplo n.º 16
0
from crypt import Crypt

c = Crypt()
a = c.encrypt('12345')
print(a)
b = c.decrypt(a)
print(b)