def __init__(self, secret=None): self.mod = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF self.modOrder = (self.mod-1) / 2 self.gen = 2 self.match = False self.crypto = crypto.Crypto() self.secret = self.crypto.mapStringToInt(secret)
def __init__(self, market_symbol): self.market_symbol = market_symbol self.timeframe = '1d' self.limit = None self.crypto_client = crypto.Crypto( None, 'bittrex' ) # defaults to using Bittrex client for looking up exchange rates to USDT self.init_logger()
def __init__(self, portfolio_name): self.trade_fee = Decimal(0.0025) self.crypto_client = crypto.Crypto( None, 'bittrex' ) # defaults to using Bittrex client for looking up exchange rates to USDT self.init_logger() self.portfolio, _created = Portfolio.get_or_create(name=portfolio_name) self.log("Using portfolio %s (%s) " % (self.portfolio.name, self.portfolio.id))
def test_key_to_store(): crypto = Crypto.Crypto() input_string = ["hello", ""] flag = 1 for i in input_string: if crypto.key_to_store(i) == SHA256.new(i.encode()).hexdigest(): flag = flag & 1 else: flag = 0 assert flag == 1
def test_view_entry(): notes.input = lambda t: 'q' crypto = Crypto.Crypto() title = "found in this world" content = "Batman is found!!!" password = "******" content_1 = crypto.encrypt(content, password) password_to_store = crypto.key_to_store(password) add_entry(content_1, title, password_to_store) entry = m.Note.get(m.Note.title == title) flag = view_entry(entry, password) assert not flag
def test_diffcheck_invalid(): crypto = Crypto.Crypto() title = "lost in this world" content_1 = "Batman is forever lost!!!" content_2 = "Batman has been found!!!" password = "******" content_1 = crypto.encrypt(content_1, password) content_2 = crypto.encrypt(content_2, password) m.Versions.create(content=content_1, title='1_' + title) m.Versions.create(content=content_2, title='2_' + title) versions = list(m.Versions.select().where(m.Versions.title.contains(title)) \ .order_by(m.Versions.timestamp.desc())) diff = diffcheck('2', '1', password, 1, versions) assert diff == ''
def init_env(self): defconf=self.util.pickpath(self.config_paths) if not self.loadconfig(defconf): print(color["green"]+"Existing configuration not found. Let's setup one!") self.init_config(defconf) time.sleep(3) self.util.clear() self.crypto=crypto.Crypto(self.conf["crypto-config"]) if self.crypto.ready != True: print(color["red"]+"Problem while setting up crypto configuration. exiting now!") sys.exit(1) return self.check_tools()
def test_view_previous_versions(): notes.input = lambda t: 'q' crypto = Crypto.Crypto() title = "lost in this world" content = "Batman is forever lost!!!" password = "******" password_to_store = crypto.key_to_store(password) # Need to encrypt before storing m.Note.create(content=content, tags=None, title=title, password=password_to_store) m.Versions.create(content=content, title='1_' + title) entry = m.Note.get(m.Note.title == title) flag = view_previous_versions(entry, password) assert not flag
def test_encrypt(): crypto = Crypto.Crypto() input_string = [("hello", "key"), ("hello2", ""), ("", "key"), ("", "")] flag = 1 for i in input_string: text, key = i[0], i[1] answer = crypto.encrypt(text, key) while len(text) % 16 != 0: text += PADDING cipher = AES.new(crypto.key_hash(key), AES.MODE_ECB) encrypted = cipher.encrypt(text.encode()) if answer == base64.b64encode(encrypted).decode(): flag = flag & 1 else: flag = 0 assert flag == 1
def __init__(self, institution_properties, keyfile): self.current_students = [] self.chain = [] self.nodes = set() # Private properties (for this node) self.institution_name = institution_properties['name'] self.institution_signature = self.institution_name # self.institution_signature = SIGN(self.institution_name) self.institution_public_key = institution_properties['public_key'] self.institution_private_key = institution_properties['private_key'] self.ciph = crypto.Crypto() self.pubKey = RSA.importKey(self.institution_public_key) self.privKey = RSA.importKey(self.institution_private_key) # Create the genesis block self.new_block(previous_hash='1', proof=100)
def test_edit_entry(): crypto = Crypto.Crypto() title = "lost in this world" content = "Batman is forever lost!!!" password = "******" password_to_store = crypto.key_to_store(password) # Need to encrypt before storing m.Note.create(content=content, tags=None, title=title, password=password_to_store) m.Versions.create(content=content, title='1_' + title) entry = m.Note.get(m.Note.title == title) new_title = "Superhero Found" new_content = "Robin to the rescue!!!" encryped_data = crypto.encrypt(new_content, password) edit_entry(entry, new_title, new_content, password) entry = m.Note.select().where(m.Note.title == title) # pylint: disable=assignment-from-no-return flag = 1 entry = m.Note.get(m.Note.title == new_title) assert (entry.title, entry.content, entry.password, flag) ==\ (new_title, encryped_data, password_to_store, 1)
def __init__(self, raw_media, parent_sdp=None): assert type(raw_media) is str or type(raw_media) is raw.media.Media assert parent_sdp is None or type( parent_sdp) is session_description.SessionDescription if type(raw_media) == str: self.__raw_media = raw.media.Media(raw_media) else: self.__raw_media = raw_media self.__parent_sdp = parent_sdp #self.__pt_reserver = self.__parent_sdp.pt_reserver if self.__parent_sdp else PayloadTypeReserver() self.__ice = ice.Ice(self.__raw_media.attributes) self.__direction = direction.Direction(self.__raw_media.attributes) self.__sdp_codec_collection = sdp_codec.SdpCodecCollection( self.__raw_media) self.__mid = mid.Mid(self.__raw_media.attributes) self.__crypto = crypto.Crypto(self.__raw_media.attributes) self.__streams = stream.StreamCollection(self.__raw_media.attributes) self.__rtcp_mux = rtcp.RtcpMux(self.__raw_media.attributes) self.__rtcp = rtcp.Rtcp(self.__raw_media.attributes) self.__ptime = ptime.Ptime(self.__raw_media.attributes) self.__silence_supp = silence_supp.SilenceSupp( self.__raw_media.attributes)
def __init__(self): self.cached_open_orders = None # memoize self.cached_unique_currencies = None # Set self.crypto_client = crypto.Crypto( None, 'bittrex') # defaults to using Bittrex client self.init_logger()
from pathlib import Path import hashlib import difflib from peewee import * # pylint: disable=redefined-builtin,wildcard-import from clint.textui import puts, colored import models as m from utils import clear_screen, get_paginated_entries import crypto as Crypto import upload_to_drive import download_from_drive PATH = os.getenv('HOME', os.path.expanduser('~')) + '/.notes' DB = SqliteDatabase(PATH + '/diary.db') m.proxy.initialize(DB) FINISH_KEY = "ctrl+Z" if os.name == 'nt' else "ctrl+D" crypto = Crypto.Crypto() #pylint disable=invalid-name profile = None #pylint disable=invalid-name def reset_profile(): """Reset the password""" global profile #pylint disable=global-statement, invalid-name profile = None def set_profile(): """Use one password for all notes""" while True: password = getpass.getpass("Password for this session: ") if not password: print("Please input a valid password")
#!/usr/bin/env python3 import os from aiohttp.web import Application, Request, RouteTableDef, json_response, run_app, FileResponse import crypto routes = RouteTableDef() @routes.get('/') async def index(request: Request): return FileResponse('index.html') @routes.post('/api/sign') async def sign(request: Request): data = await request.json() signature = request.app['crypto'].sign(data['data']) return json_response(signature) app = Application() app['crypto'] = crypto.Crypto(key=os.getenv('keyfile', 'signkey.pem'), password=os.getenv('pw')) app.add_routes(routes) app.router.add_static('/', path='static', name='static') run_app(app, host='0.0.0.0', port=os.getenv('port', 80))
def init_config(self,config): if not type(config) is str: config=self.util.numeric_choice("Where should the configuration file be saved:",self.config_paths) self.conf={} ''' Downloading with system tools is an intentional decision. This is one wheel that will not be re-invented here. aria2c and other downloaders will be added here in the future. ''' self.conf["fetchtool"]=self.util.numeric_choice("Which tool should be used to download files:",["curl","wget"]) self.conf["downloads"]=self.util.numeric_choice_flexible("Where should downloaded files be saved:",[os.getenv('HOME')+"/Downloads/",os.getenv('HOME')+"/",os.getenv('HOME')+"/DownloadHygeine/"]) self.util.mkdirs(self.conf["downloads"]) mirrors=self.util.yesno_choice("Do you want downloads to use mirrors? ") if mirrors==True: self.conf["mirrors"]=1 self.conf["mirrorselect"]=self.util.numeric_choice("How should download mirrors be chosen?",["Round-Robin","Random"]) #TODO: least latency mirror selection else: self.conf["mirrors"]=0 if self.util.yesno_choice("Do you want to use a git repository different than https://github.com/hackers-terabit/downloadhygeine-catalog for the download catalog management?"): self.conf["gitrepo"]=raw_input("Please enter the URL of a valid git repository: ") print(color["green"]+"Got it! Will use "+self.conf["gitrepo"]+" As the download catalog repository."+color["white"]+"\n>") else: self.conf["gitrepo"]="https://github.com/hackers-terabit/downloadhygeine-catalog" print(color["green"]+"Great, will use the default git repository "+self.conf["gitrepo"]+" to manage the download catalog") while True: self.conf["localclone"]=self.util.numeric_choice_flexible("Where should the download catalogue be stored?",[os.getenv('HOME')+"/Downloads/downloadhygeine-catalog",os.getenv('HOME')+"/downloadhygeine-catalog"]) if os.path.exists(self.conf["localclone"]): break elif os.path.exists(os.path.abspath(self.conf["localclone"])): self.conf["localclone"]=os.path.abspath(self.conf["localclone"]) break elif self.util.mkdirs(os.path.abspath(self.conf["localclone"])): self.conf["localclone"]=os.path.abspath(self.conf["localclone"]) break else: print(color["red"]+"The file system path:"+self.conf["localclone"]+" Does not exist, please enter a different valid path"+color["white"]+"\n>") torrents=self.util.yesno_choice("Should torrent downloads be enabled?") if torrents: self.conf["torrents"]=1 while True: self.conf["torrentapp"]=self.util.numeric_choice_flexible("Where in your filesystem is your torrent application located?",["/usr/bin/rtorrent","/usr/bin/ktorrent","/usr/bin/transmission"]) if os.path.exists(os.path.abspath(self.conf["torrentapp"])): break else: print("Error, the specified path '"+self.conf["torrentapp"]+"' Does not exist.") self.conf["torrentoptions"]=raw_input("What command-line options should be passed to the torrent application? (Leave blank and hit enter if none)\n:") else: self.conf["torrents"]=0 crypto_config={} crypto_config["trusted_keys_path"]=self.util.numeric_choice_flexible(color["green"]+"Where should trusted public keys be stored:",[os.getenv('HOME')+"/.download-hygeine.trusted_keys"]) with open(crypto_config["trusted_keys_path"],"war+") as f: #check if we can write to this file. f.write("") crypto_config["ECDSA-CURVE"]="secp521r1" crypto_config["hash"]="SHA512" print(color["blue"]+"This is the current(default) configuration for digital signatures. This configuration will be used to sign and verify download catalogs:\n------------") print(color["blue"]+json.dumps(crypto_config,indent=4,sort_keys=True)) print(color["blue"]+"------------") if self.util.yesno_choice("Would you like to change any of these paramters? (Pick 'N' unless you know what you are doing here)"): choice=self.util.numeric_choice("Select one of the following paramters to change: ",["Signature Hash","ECDSA-CURVE"]) if choice=="ECDSA-CURVE": crypto_config["ECDSA-CURVE"]=self.util.numeric_choice("Pick from one the following availble curves:",list(crypto.Crypto.curvemap)) elif choice=="Signature Hash": crypto_config["hash"]=self.util.numeric_choice("Pick from one the following availble hash algorithms:",list(crypto.Crypto.hash_algorithms)) self.crypto=crypto.Crypto(crypto_config) crypto_config=self.crypto.config self.conf["crypto-config"]=self.crypto.config try: with open(config,"w+") as cf: cf.write(json.dumps(self.conf,indent=4,sort_keys=True)) os.chown(config,os.getuid(),os.getgid()) #make sure the current user owns this file. os.chmod(config,0o0600) #owner read/write,nobody else can rwx it. except Exception as e: print(color["red"]+"Error saving the configuration file at: "+config) print(traceback.print_exc()) print(color["white"]+">") return print(color["blue"]+"Finished saving your new configuration. ") return
return (ip[0] + "." + ip[1] + ".XXX.XXX") if ":" in ip_address: ip = ip_address.split(":") return (ip[0] + ":" + ip[1] + ":XXX:XXX") if not anonymize: return ip_address if __name__ == "__main__": logging.basicConfig(filename="server.log", level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s") logging.getLogger("tornado.access").disabled = True logging.getLogger("tornado.application").disabled = True database = database.Database() crypto = crypto.Crypto() application = tornado.web.Application([(r"/api", MainHandler), (r"/pk", PubKeyHandler)]) # Because server should run behind a proxy -> xheaders=True application.listen(8888, xheaders=True) try: logging.info("Start server ...") tornado.ioloop.IOLoop.current().start() finally: logging.info("Server has been stopped!")
def __init__(self): self.mycrypto = crypto.Crypto() self.database = ""