def cryptPrivatekeyToAddress(self, privatekey=None): from Crypt import CryptArk if not privatekey: # If no privatekey in args then ask it now import getpass privatekey = getpass.getpass("Private key (input hidden):") print CryptArk.privatekeyToAddress(privatekey)
def siteCreate(self, passphrase=False): logging.info("Generating new privatekey...") from Crypt import CryptArk if passphrase: import getpass passphrase = getpass.getpass( "Type your passphrase (input hidden): ") privatekey = hashlib.sha256( passphrase if isinstance(passphrase, bytes) else passphrase. encode("utf-8")).hexdigest() else: privatekey = CryptArk.newPrivatekey() logging.info( "----------------------------------------------------------------------" ) logging.info("Site private key: %s" % privatekey) logging.info( " !!! ^ Save it now, required to modify the site ^ !!!" ) address = CryptArk.privatekeyToAddress(privatekey) w_address = CryptArk.getAddress(address) logging.info("Site address: %s" % w_address) logging.info( "----------------------------------------------------------------------" ) while True and not config.batch: if raw_input("? Have you secured your private key? (yes, no) > " ).lower() == "yes": break else: logging.info( "Please, secure it now, you going to need it to modify your site!" ) logging.info("Creating directory structure...") from Site import Site from Site import SiteManager SiteManager.site_manager.load() folder_name = w_address os.mkdir("%s/%s" % (config.data_dir, folder_name)) open("%s/%s/index.html" % (config.data_dir, folder_name), "w").write("Hello %s!" % address) logging.info("Creating content.json...") site = Site(w_address, public_key=address) site.content_manager.sign(privatekey=privatekey, extend={"postmessage_nonce_security": True}) site.settings["own"] = True site.saveSettings() logging.info("Site created!")
def getNewSiteData(self): import random bip32_index = random.randrange(2**256) % 100000000 site_privatekey = CryptArk.hdPrivatekey(self.master_seed, bip32_index) site_address = CryptArk.privatekeyToAddress(site_privatekey) if site_address in self.sites: raise Exception("Random error: site exist!") # Save to sites self.getSiteData(site_address) self.sites[site_address]["privatekey"] = site_privatekey self.saveDelayed() return site_address, bip32_index, self.sites[site_address]
def addCert(self, auth_address, domain, auth_type, auth_user_name, cert_sign): try: address = CryptArk.getAddress(address) except: pass # Find privatekey by auth address auth_privatekey = [ site["auth_privatekey"] for site in self.sites.values() if site["auth_address"] == auth_address ][0] cert_node = { "auth_address": auth_address, "auth_privatekey": auth_privatekey, "auth_type": auth_type, "auth_user_name": auth_user_name, "cert_sign": cert_sign } # Check if we have already cert for that domain and its not the same if self.certs.get(domain) and self.certs[domain] != cert_node: return False elif self.certs.get(domain) == cert_node: # Same, not updated return None else: # Not exist yet, add self.certs[domain] = cert_node self.save() return True
def generateAuthAddress(self, address): s = time.time() try: address = CryptArk.getAddress(address) except: pass address_id = self.getAddressAuthIndex( address) # Convert site address to int auth_privatekey = CryptArk.hdPrivatekey(self.master_seed, address_id) self.sites[address] = { "auth_address": CryptArk.privatekeyToAddress(auth_privatekey), "auth_privatekey": auth_privatekey } self.saveDelayed() self.log.debug("Added new site: %s in %.3fs" % (address, time.time() - s)) return self.sites[address]
def deleteSiteData(self, address): try: address = CryptArk.getAddress(address) except: pass if address in self.sites: del (self.sites[address]) self.saveDelayed() self.log.debug("Deleted site: %s" % address)
def getCert(self, address): try: address = CryptArk.getAddress(address) except: pass site_data = self.getSiteData(address, create=False) if not site_data or "cert" not in site_data: return None # Site dont have cert return self.certs.get(site_data["cert"])
def __init__(self, master_address=None, master_seed=None, data={}): if master_seed: self.master_seed = master_seed self.master_address = CryptArk.privatekeyToAddress( self.master_seed) elif master_address: self.master_address = master_address self.master_seed = data.get("master_seed") else: self.master_seed = CryptArk.newSeed() self.master_address = CryptArk.privatekeyToAddress( self.master_seed) self.sites = data.get("sites", {}) self.certs = data.get("certs", {}) self.settings = data.get("settings", {}) self.delayed_save_thread = None self.log = logging.getLogger("User:%s" % self.master_address)
def setSiteSettings(self, address, settings): try: address = CryptArk.getAddress(address) except: pass site_data = self.getSiteData(address) site_data["settings"] = settings self.saveDelayed() return site_data
def getAuthPrivatekey(self, address, create=True): try: address = CryptArk.getAddress(address) except: pass cert = self.getCert(address) if cert: return cert["auth_privatekey"] else: return self.getSiteData(address, create)["auth_privatekey"]
def getCertUserId(self, address): try: address = CryptArk.getAddress(address) except: pass site_data = self.getSiteData(address, create=False) if not site_data or "cert" not in site_data: return None # Site dont have cert cert = self.certs.get(site_data["cert"]) if cert: return cert["auth_user_name"] + "@" + site_data["cert"]
def getSiteData(self, address, create=True): try: address = CryptArk.getAddress(address) except: pass if address not in self.sites: # Generate new BIP32 child key based on site address if not create: return { "auth_address": None, "auth_privatekey": None } # Dont create user yet self.generateAuthAddress(address) return self.sites[address]
def setCert(self, address, domain): try: address = CryptArk.getAddress(address) except: pass site_data = self.getSiteData(address) if domain: site_data["cert"] = domain else: if "cert" in site_data: del site_data["cert"] self.saveDelayed() return site_data
def getEncryptPrivatekey(self, address, param_index=0): assert param_index >= 0 and param_index <= 1000 site_data = self.getSiteData(address) if site_data.get("cert"): # Different privatekey for different cert provider index = param_index + self.getAddressAuthIndex(site_data["cert"]) else: index = param_index if "encrypt_privatekey_%s" % index not in site_data: address_index = self.getAddressAuthIndex(address) crypt_index = address_index + 1000 + index site_data["encrypt_privatekey_%s" % index] = CryptArk.hdPrivatekey(self.master_seed, crypt_index) self.log.debug("New encrypt privatekey generated for %s:%s" % (address, index)) return site_data["encrypt_privatekey_%s" % index]
def __init__(self, address, allow_create=True, settings=None, public_key=None): if public_key: self.address = CryptArk.getAddress(public_key) self.publicKey = public_key else: self.address = address self.publicKey = SiteManager.getPublicKey(address) self.address_hash = hashlib.sha256(self.address).digest() self.address_short = "%s..%s" % (self.address[:6], self.address[-4:]) # Short address for logging self.log = logging.getLogger("Site:%s" % self.address_short) self.addEventListeners() self.content = None # Load content.json self.peers = {} # Key: ip:port, Value: Peer.Peer self.peers_recent = collections.deque(maxlen=100) self.peer_blacklist = SiteManager.peer_blacklist # Ignore this peers (eg. myself) self.worker_manager = WorkerManager(self) # Handle site download from other peers self.bad_files = {} # SHA check failed files, need to redownload {"inner.content": 1} (key: file, value: failed accept) self.content_updated = None # Content.js update time self.notifications = [] # Pending notifications displayed once on page load [error|ok|info, message, timeout] self.page_requested = False # Page viewed in browser self.websockets = [] # Active site websocket connections self.connection_server = None self.loadSettings(settings) # Load settings from sites.json self.storage = SiteStorage(self, allow_create=allow_create) # Save and load site files self.content_manager = ContentManager(self) self.content_manager.loadContents() # Load content.json files if "main" in sys.modules and "file_server" in dir(sys.modules["main"]): # Use global file server by default if possible self.connection_server = sys.modules["main"].file_server else: self.log.debug("Creating connection server") # remove self.connection_server = FileServer() self.announcer = SiteAnnouncer(self) # Announce and get peer list from other nodes if not self.settings.get("auth_key"): # To auth user in site (Obsolete, will be removed) self.settings["auth_key"] = CryptHash.random() self.log.debug("New auth key: %s" % self.settings["auth_key"]) if not self.settings.get("wrapper_key"): # To auth websocket permissions self.settings["wrapper_key"] = CryptHash.random() self.log.debug("New wrapper key: %s" % self.settings["wrapper_key"]) if not self.settings.get("ajax_key"): # To auth websocket permissions self.settings["ajax_key"] = CryptHash.random() self.log.debug("New ajax key: %s" % self.settings["ajax_key"])
def __init__(self, site, allow_create=True): self.site = site try: w_address = CryptArk.getAddress(self.site.address) except: w_address = False self.directory = u"%s/%s" % ( config.data_dir, w_address if w_address else self.site.address ) # Site data diretory self.allowed_dir = os.path.abspath( self.directory) # Only serve file within this dir self.log = site.log self.db = None # Db class self.db_checked = False # Checked db tables since startup self.event_db_busy = None # Gevent AsyncResult if db is working on rebuild self.has_db = self.isFile("dbschema.json") # The site has schema if not os.path.isdir(self.directory): if allow_create: os.mkdir(self.directory) # Create directory if not found else: raise Exception("Directory not exists: %s" % self.directory)
def cryptSign(self, message, privatekey): from Crypt import CryptArk print CryptArk.sign(message, privatekey)
def cryptVerify(self, message, sign, address): from Crypt import CryptArk print CryptArk.verify(message, address, sign)
def cryptGetPrivatekey(self, master_seed, site_address_index=None): from Crypt import CryptArk print CryptArk.hdPrivatekey(master_seed, site_address_index)