def from_dict(cls, config): cls.public_key = config['public_key'] cls.address = str( P2PKHBitcoinAddress.from_pubkey(cls.public_key.decode('hex'))) cls.private_key = config['private_key'] cls.username = config['username'] cls.wif = cls.to_wif() cipher = Crypt(str(cls.private_key)) cls.bulletin_secret = cls.get_bulletin_secret() cls.mongodb_host = config['mongodb_host'] cls.database = config['database'] cls.site_database = config['site_database'] cls.web_server_host = config['web_server_host'] cls.web_server_port = config['web_server_port'] if config['peer_host'] == '0.0.0.0' or config[ 'peer_host'] == 'localhost': raise Exception( "cannot use localhost or 0.0.0.0, must specify public ipv4 address" ) if config['peer_host'] == '[my public ip]': raise Exception( "please configure your peer_post to your public ipv4 address") cls.peer_host = config['peer_host'] cls.peer_port = config['peer_port'] cls.serve_host = config['serve_host'] cls.serve_port = config['serve_port'] cls.callbackurl = config['callbackurl'] cls.fcm_key = config['fcm_key']
def read_config(config_file=""): config = {} if config_file == "": file = open("/home/pi/fireball_camera/config.txt", "r") else: file = open(config_file, "r") for line in file: line = line.strip('\n') #print (line) #Find first index of = c = line.index('=') config[line[0:c]] = line[c + 1:] try: test = config['hd'] except: config['hd'] = 0 if 'cam_pwd' in config: try: #We decrypt the cam password if it is crypted c = Crypt() config['cam_pwd'] = c.decrypt(config['cam_pwd']) except: config['cam_pwd'] = config['cam_pwd'] else: config['cam_pwd'] = 'xrp23q' file.close() return (config)
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.")
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 __init__(self, masterkey, url, notice=False, debug=False): self.parser = URLParser(url) self.domain = self.parser.getDomain() self.notice = notice enc = Crypt(masterkey) self.public_key = enc.getPublicKey(self.domain) self.sqrlreq = SQRLRequest(self.parser, self.public_key) unsigned_url = self.sqrlreq.get_url() self.signed_url = enc.sign(unsigned_url) self.debug = debug
def _write(self): pos = 0 # write data entries first for key in self.files: fi = self.files[key] # read data f = open(fi.datafile, 'rb') data = f.read() f.close() fi._crc = crc32(data) & 0xffffffff fi._uncompressed_length = len(data) # check for extension _, extension = os.path.splitext(fi.filename) if extension in UNCOMPRESSED_EXT: # write data uncompressed fi._compressed_length = fi.uncompressed_length else: # compress data deflater = zlib.compressobj(6, zlib.DEFLATED, -15) data = deflater.compress(data) data += deflater.flush() fi._compressed_length = len(data) deflater = None if self.enable_encryption and fi.supports_encryption(): data = Crypt().encrypt(data) self.file_handle.write(data) # update file info fi._data_offset = pos pos += fi.compressed_length self._filetable_offset = pos # write the file table for key in self.files: fi = self.files[key] buf = fi.to_buffer() self.file_handle.write(buf) pos += len(buf) # write archive footer buf = struct.pack('<HIHI4sII', len(self.files), self._filetable_offset, 0, pos, SUPPORTED_FORMATS[0], self.base_revision, self.revision) self.file_handle.write(buf)
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')
def read_config(): logging.debug('Reading Config.txt') config = {} try: file = open("/home/pi/fireball_camera/config.txt", "r") for line in file: line = line.strip('\n') #Find first index of = if('=' in line): c = line.index('=') config[line[0:c]] = line[c+1:] config['hd'] = 0 if 'cam_pwd' in config: try: #We decrypt the cam password if it is crypted c = Crypt() config['cam_pwd'] = c.decrypt(config['cam_pwd']) logging.debug('cam_pwd successfully decrypted') except: config['error'] = "Impossible to decrypt the password - password must only contains characters and digits" logging.error('Impossible to decrypt ' + str(config['cam_pwd'])) logging.debug('Config (ERROR) ' + str(config)) file.close() logging.debug('Result ' + str(config) ) return(config) except: config['error'] = 'The config file cannot be read, please check your config.txt file'; logging.error('Error in config.txt') logging.debug('Config (ERROR) ' + str(config)) return config;
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()
def write_config(cls, server, username, password): """ Write config file and save modification time """ log.debug( f"Writing config file: {server} {username} {password} {cls.VERIFY_SSL_CERT}" ) crypto = Crypt(username, password) cls.PATH_CONFIG_DIR.mkdir(parents=True, exist_ok=True) cls.PATH_CONFIG_FILE.touch(exist_ok=True) config = configparser.ConfigParser() config["settings"] = { "server": server, "username": username, "hash_login": crypto.pw_hash_login, "hash_msg": crypto.pw_hash_msg, "verify_ssl_cert": cls.VERIFY_SSL_CERT, } with open(cls.PATH_CONFIG_FILE, "w") as configfile: config.write(configfile) if not cls.CONFIGFILE_MTIME: cls.CONFIGFILE_MTIME = Path(cls.PATH_CONFIG_FILE).stat().st_mtime return True
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])
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])
def get_data(self, filename, archive=None): """ Returns the uncompressed data of `filename` in the archive. Args: filename: The name of the file. archive: The name of the archive. Defaults to the current archive Returns: A string of uncompressed data. If the file could not be found, None is returned. """ info = self.get(filename, archive) if info is None: return None self.file_handle.seek(info.data_offset) data = self.file_handle.read(info.compressed_length) if self.enable_encryption and info.supports_encryption(): data = Crypt().decrypt(data) if info.compressed_length == info.uncompressed_length: return data return zlib.decompress(data, -15)
return [date_parsed, hour_parsed] def parse_date_time(date_time): all_date_parsed = str(date_time).split(' ') date_parsed = all_date_parsed[0].split('-') hour_parsed = all_date_parsed[1].split(':') return [date_parsed, hour_parsed] 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: (? para ajuda)') bearer_token = str(input('')).strip() if bearer_token == '?': tutorial()
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
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 __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 __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 encout(filename, data): with open(filename, 'w') as outfile: outfile.write(data) def decin(filename): data = open(filename).read() return data #################################################################################################### ## file read #################################################################################################### fileobj = open(sys.argv[1]) msg = bytes(fileobj.read(), "utf-8") #################################################################################################### ccc = Crypt() key = bytes(sys.argv[1], "utf-8") #encrypted = ccc.encrypt(key, msg) #decrypted = ccc.decrypt(key, encrypted) #encout('enc_' + sys.argv[1], encrypted) fileenc = decin('enc_test') decrypted = ccc.decrypt(key, fileenc) #print(encrypted) print(decrypted)