def _get_key(self): # EKE algorithm client_key = Random.get_random_bytes(16) password = get_password(self._filename) ciphertext = encrypt(password, client_key) self._send(ciphertext) # Get session key double encrypted ciphertext = self._recv(80) ciphertext = decrypt(password, ciphertext) self._key = decrypt(client_key, ciphertext) # Check key r_a = Random.get_random_bytes(16) ciphertext = encrypt(self._key, r_a) self._send(ciphertext) ciphertext = self._recv(64) r_ab = decrypt(self._key, ciphertext) if r_ab[:16] != r_a: raise ValueError('r_a invalid') r_b = r_ab[16:] ciphertext = encrypt(self._key, r_b) self._send(ciphertext) print('Secure connection established')
def changeMasterPwd(self, newPwd): oldPwd = config.getMasterPwd() conn = self.getConnection() mDao = MasterPwdDao(conn) pDao = PwdDao(conn) # 1st re-encrypt all passwords with the new master password accountList = pDao.getAllPwd() currentDate = unicode(datetime.datetime.today()) for account in accountList: dePwd = util.decrypt(oldPwd, account.pwd) enPwd = util.encrypt(newPwd, dePwd) if account.secret: deSecret = util.decrypt(oldPwd, account.secret) enSecret = util.encrypt(newPwd, deSecret) else: enSecret = '' deUsername = util.decrypt(oldPwd, account.username) enUsername = util.encrypt(newPwd, deUsername) pDao.updateAccount(account.id, account.title, account.description, enUsername, enPwd, enSecret, currentDate) # 2nd get md5 of new master password, update the masterpassword table newMD5String = util.md5Encoding(newPwd) mDao.updateMasterPwd(newMD5String) # 3rd update master password in config module config.setMasterPwd(newPwd) conn.commit() conn.close()
def __init__(self, conf): print("Running SplunkAPI...") self.CONF = conf self.splunk_client = client.connect( host=conf['hostname'], port=conf['port'], username=decrypt(conf['username']), password=decrypt(conf['password']), ) assert isinstance(self.splunk_client, client.Service)
def __init__(self, conf): self.range_data = {} print("Running InfobloxAPI...") self.VLAN_FILEPATH = conf['offline_path'] self.connector_opts = { 'host': conf['hostname'], 'ssl_verify': True, 'username': decrypt(conf['username']), 'password': decrypt(conf["password"]) }
def showHidePwd(self): if self.checkBox.isChecked(): # show self.password.setStyleSheet('') self.secret.setStyleSheet('') self.password.setText(util.decrypt(config.getMasterPwd(), self.accountObj.pwd)) self.secret.setPlainText(util.decrypt(config.getMasterPwd(), self.accountObj.secret).decode('utf-8') if self.accountObj.secret else '') else: # hide self.password.setStyleSheet("background-color: black; color: rgb(192, 0, 0);") self.secret.setStyleSheet("background-color: black; color: rgb(192, 0, 0);") self.password.setText(myGui.INFO_HIDE_TXT) self.secret.setPlainText(myGui.INFO_HIDE_TXT)
def __init__(self, conf, subnet_data=None, filter_settings=None): print("Running QualysAPI...") self.HOSTNAME = conf['hostname'] self.REPORT_CALL = conf['report_call'] self.REPORT_NAME = conf['report_name'] self.AUTH = (decrypt(conf['username']), decrypt(conf['password'])) self.SAVE_PATH = conf['save_path'] self.HEADERS = {'X-Requested-With': 'Python'} self.REPORT_CACHE = ".latest_report" self.vuln_data = {} self.host_data = {}
def init(self, name, password, dataDir, port, host=None): """ Method to initialize a server component. :param name: Name of the component to be initialized. """ pgcCmd = PGC_HOME + os.sep + "pgc --json init " + name + " --datadir " + dataDir + " --port " + port if port == '': pgcCmd = pgcCmd.split(' --port')[0] if dataDir == '': pgcCmd = pgcCmd.split(' --datadir')[0] if host: pgc_host_info = util.get_pgc_host(host) cred_info = util.get_credentials_by_uuid( pgc_host_info.get('ssh_cred_id')) enc_secret = util.get_value("GLOBAL", "SECRET", "") enc_key = "{0}{1}".format(enc_secret, cred_info.get("cred_uuid")) ssh_username = cred_info.get("ssh_user") password = "" if cred_info.get("ssh_passwd"): password = util.decrypt(cred_info.get("ssh_passwd"), enc_key) ssh_key = "" if cred_info.get("ssh_key"): ssh_key = util.decrypt(cred_info.get("ssh_key"), enc_key) sudo_pwd = "" if cred_info.get("ssh_sudo_pwd"): sudo_pwd = util.decrypt(cred_info.get("ssh_sudo_pwd"), enc_key) ssh_host = pgc_host_info.get('host') from PgcRemote import PgcRemote remote = PgcRemote(ssh_host, ssh_username, password=password, ssh_key=ssh_key) remote.connect() is_file_added = remote.add_file('/tmp/.pgpass', password) remote.disconnect() pgcCmd = pgcCmd + " --pwfile /tmp/.pgpass --host \"" + host + "\"" if util.is_postgres(name) and not host: pgpass_file = PGC_HOME + os.sep + name + os.sep + ".pgpass" if not os.path.isfile(pgpass_file): password_file = open(pgpass_file, 'w') password_file.write(password + '\n') password_file.close() os.chmod(pgpass_file, 0600) pgcProcess = subprocess.Popen(pgcCmd, stdout=subprocess.PIPE, shell=True) for line in iter(pgcProcess.stdout.readline, ''): try: ln = (line).rstrip('\n') if type(eval(ln)) is list: yield self.session.publish('com.bigsql.onInit', ln) except: pass
def share_data(self, user_data, user_cert, service_provider_cert): # get the latest transaction for the user latest_tx_hash = self.latest_tx_list[user_cert] latest_tx = self.transaction_pool[latest_tx_hash] key = self.keys[latest_tx_hash] # get the action from the transaction and decrypt the data decrypted = decrypt(key, latest_tx.action.get_data()) message, _signature = split_data(decrypted) # check that the data to share matches the data on record is_consistent = check_data_consistency(json.loads(user_data.data), json.loads(message)) # if it is not consistent, do not add the action to a transaction if not is_consistent: return None # if it is consistent, create a user share action new_share_action = UserDataShareAction(user_data, service_provider_cert) # create a transaction for the action transaction = Transaction(self.last_transaction_hash, new_share_action) # add the transaction to the chain and return the hash pointer return self.add_transaction_to_chain(transaction)
def getPwdById(self,pwdId): conn = self.getConnection() pwdDao = PwdDao(conn) result = pwdDao.getPwdById(pwdId) result.username = util.decrypt(config.getRootPwd(), result.username) conn.close() return result
def _decrypt_data(self, data): new_data = {} for i, v in data.iteritems(): vp = v.copy() vp["target"] = util.decrypt(self.keypair, v["target"]) new_data[i] = vp return new_data.copy()
def onCopyPassword(self): account = self.pwdFunc.getPwdByID(self.selectedPwdID) # decrypt password dePwd = util.decrypt(config.getMasterPwd(), account.pwd) clipboard = QtGui.QApplication.clipboard() clipboard.setText(dePwd) myGui.showInfoDialog(myGui.INFO_CLIPBOARD, account.title)
def test_add_user_data(ident_service): # No transactions in the chain yet assert ident_service.last_transaction_hash == b'Base' # Create the data and signature data = json.dumps({'first_name': 'Bob', 'last_name': 'Smith'}).encode() signature = sign(user_1_private_key, data) user_data = UserData(data, signature) # Add the data to the service tx_hash = ident_service.add_user_data(user_data, user_1_cert_string) # Ensure the head of the chain is the new transaction assert tx_hash == ident_service.last_transaction_hash # Get the transaction and encryption key tx = ident_service.get_transaction(tx_hash) key = ident_service.get_key(tx_hash) # Ensure the transaction points to the old head of the chain assert tx.hash_pointer == b'Base' # Get the message and signature from the transaction decrypted = decrypt(key, tx.action.get_data()) message, signature = split_data(decrypted) # Ensure the data has not been tampered with verify(user_1_cert, message, signature) # Ensure the data matches what the user uploaded assert message == data
def getPwdById(self, pwdId): conn = self.getConnection() pwdDao = PwdDao(conn) result = pwdDao.getPwdById(pwdId) result.username = util.decrypt(config.getRootPwd(), result.username) conn.close() return result
def read(email, password_b64, db_server, do_network, scrypt_server): keys = build_PWK(email, password_b64, scrypt_server, do_network) PWK_b64, MAC_b64, SRPpw_b64 = keys SRPsession = do_SRP(db_server, email, SRPpw_b64, do_network) resp = do_request(SRPsession, ["get"], do_network, db_server) if resp[0] != "ok": raise Oops("server reject") WUK_b64 = resp[1] UK_b64 = decrypt(PWK_b64, MAC_b64, WUK_b64) return UK_b64, SRPpw_b64
def test_encrypt_decrypt(self): # roundtrip to ensure we can recover original plaintext password = b'potato' salt = util.make_salt() plain_text = b'the cat meows twice at midnight' cipher_text = util.encrypt(password, salt, plain_text) deciphered_text = util.decrypt(password, salt, cipher_text) self.assertEqual(plain_text, deciphered_text)
def changeRootPwd(self, newRootPwd): oldPwd = config.getRootPwd() conn = self.getConnection() masterDao = MasterDao(conn) pwdDao = PwdDao(conn) # 1 re-encrypt all passwords with new root pwd accountList = pwdDao.getAllPasswd() currentDate = datetime.datetime.today() for account in accountList: dePassword = util.decrypt(oldPwd, account.pwd) enPassword = util.encrypt(newRootPwd, dePassword) if account.secret: deSecret = util.decrypt(oldPwd, account.secret) enSecret = util.encrypt(newRootPwd, deSecret) else: enSecret = "" deUsername = util.decrypt(oldPwd, account.username) enUsername = util.encrypt(newRootPwd, deUsername) account.pwd = enPassword account.username = enUsername account.secret = enSecret account.lastupdate = currentDate pwdDao.updateAccount(account.id, account.title, account.description, account.username, account.pwd, account.secret, account.lastupdate) # 2 get md5 of new root pwd, update the rootpassword table newMd5String = util.md5Encode(newRootPwd) masterDao.updateMasterPwd(newMd5String) # 3 update master password in config module. config.setRootPwd(newRootPwd) conn.commit() conn.close()
def loadData(self): acc = self.accountObj self.title.setText(acc.title) self.description.setPlainText(acc.description) self.account.setText(acc.username) self.secret.setPlainText(util.decrypt(config.getMasterPwd(), acc.secret).decode('utf-8') if acc.secret else '') tagName = [tag.name for tag in acc.tags] cnt = self.tags.count() for idx in xrange(cnt): if unicode(self.tags.item(idx).text()) in tagName: self.tags.item(idx).setSelected(True)
def send_rcon_command(self, command, raise_errors=False, num_retries=3, timeout=3.0): encRcon = util.decrypt(dbKey, self.rcon_password) if encRcon is None: encRcon = self.rcon_password return util.send_rcon_command(self.ip_string, self.port, encRcon, command, raise_errors, num_retries, timeout)
def changeRootPwd(self,newRootPwd): oldPwd = config.getRootPwd() conn = self.getConnection() masterDao = MasterDao(conn) pwdDao = PwdDao(conn) # 1 re-encrypt all passwords with new root pwd accountList = pwdDao.getAllPasswd() currentDate = datetime.datetime.today() for account in accountList: dePassword = util.decrypt(oldPwd, account.pwd) enPassword = util.encrypt(newRootPwd, dePassword) if account.secret: deSecret = util.decrypt(oldPwd, account.secret) enSecret = util.encrypt(newRootPwd, deSecret) else: enSecret = "" deUsername = util.decrypt(oldPwd, account.username) enUsername = util.encrypt(newRootPwd, deUsername) account.pwd = enPassword account.username = enUsername account.secret = enSecret account.lastupdate = currentDate pwdDao.updateAccount(account.id,account.title, account.description, account.username, account.pwd, account.secret,account.lastupdate) # 2 get md5 of new root pwd, update the rootpassword table newMd5String = util.md5Encode(newRootPwd) masterDao.updateMasterPwd(newMd5String) # 3 update master password in config module. config.setRootPwd(newRootPwd) conn.commit() conn.close()
def aes_valid_padding(self, ciphertext, iv): """ Verifies that the decrypted ciphertext is padded according to PKCS#7. Args: ciphertext (str): The ciphertext to be decrypted. iv (str): The initialiation vector. Returns: is_valid (bool): True if decrypted ciphertext follows PKCS#7 padding format and False otherwise. """ padded_plaintext = decrypt(ciphertext, iv, self.key) return valid_pkcs7_padding(padded_plaintext, self.block_size)
def verify(self): #verify login dbstransaction = model.Session() user_record_query = dbstransaction.query(model.User).filter(model.User.user_name == self.user_name) try: result = user_record_query.one() if(result and util.decrypt(result.Hash,result.Password) == self.password): return True else: return False except: return False
def test_enc_dec_file_data(): """ Test encrypt/decrypt file content """ key = base64.urlsafe_b64encode(os.urandom(32)) with open('test_file') as f: data = f.read() c = util.encrypt(key, data) d = util.decrypt(key, c) assert d == data
def get_current_user(self): fbt_user = "" if self.get_argument("from", "chrome") == "client": fbt_user = util.g_cookie(self, "fbt_user") else: fbt_user = self.get_cookie("fbt_user") if fbt_user: user_json = util.decrypt(15, fbt_user) #print user_json if not user_json: return None return user_json else: return None
def setup(self): self._session_key = get_random_bytes(16) ciphertext = self._socket.recv(48) client_key = decrypt(self._password, ciphertext) ciphertext = encrypt(client_key, self._session_key) ciphertext = encrypt(self._password, ciphertext) self._socket.sendall(ciphertext) ciphertext = self._socket.recv(48) r_a = decrypt(self._session_key, ciphertext) r_b = get_random_bytes(16) ciphertext = encrypt(self._session_key, r_a + r_b) self._socket.sendall(ciphertext) ciphertext = self._socket.recv(48) r_b_received = decrypt(self._session_key, ciphertext) if r_b_received != r_b: raise ValueError('r_b invalid') print('Secure connection established') self._socket.settimeout(0.5)
def verify(self): #verify login dbstransaction = model.Session() user_record_query = dbstransaction.query( model.User).filter(model.User.user_name == self.user_name) try: result = user_record_query.one() if (result and util.decrypt(result.Hash, result.Password) == self.password): return True else: return False except: return False
def _handle_timeline_notification(self, data): """Handle timeline notification.""" for user_action in data.get('userActions', []): # Fetch the timeline item. item = self.mirror_service.timeline().get(id=data['itemId']).execute() item_id = data['itemId'] old_item = item logging.info(user_action.get('payload')) userid = data['userToken'] dwollaCreds = db.Query(DwollaCredentials).filter('userid =', data['userToken']).get() if user_action.get('type') == 'CUSTOM': split = re.split(r"@", user_action.get('payload')) amount = split[0] destination = split[1] pin = util.decrypt(dwollaCreds.pin, PASSWORD) try: transaction_id = DwollaUser(dwollaCreds.token).send_funds(amount, destination, pin) transaction = DwollaUser(dwollaCreds.token).get_transaction(transaction_id) logging.info("transaction info") logging.info(transaction) item['html'] = """<article> <section> Successfully paid $%s to %s! </section> </article>""" % (transaction['Amount'], transaction['DestinationName']) except DwollaAPIError, e: item['html'] = """<article> <section> An error occured: %s </section> </article>""" % (e) #find all bundle items items = self.mirror_service.timeline().list().execute() items = items['items'] #delete all except current one - need more robust error checking here logging.info('current item: ' + item_id) for i in items: if i['id'] != item_id: logging.info('delete ' + i['id']) try: self.mirror_service.timeline().delete(id=i['id']).execute() except: pass item['bundleId'] = 'dg-success' item['menuItems'] = [{ 'action': 'DELETE' }]; self.mirror_service.timeline().update(id=item['id'], body=item).execute() else: logging.info( "I don't know what to do with this notification: %s", user_action)
def server_edit(serverid): server = GameServer.query.get_or_404(serverid) is_owner = (g.user and (util.is_server_owner(g.user, server))) is_sadmin = (g.user and util.is_super_admin(g.user)) app.logger.info("Owner: {} Sadmin: {}".format(is_owner, is_sadmin)) if not is_owner: if not is_sadmin: raise BadRequestError('You do not have access to this server.') # Attempt encryption/decryption rconDecrypt = util.decrypt(dbKey, server.rcon_password) form = ServerForm(request.form, display_name=server.display_name, ip_string=server.ip_string, port=server.port, rcon_password=server.rcon_password if rconDecrypt is None else rconDecrypt, public_server=server.public_server) if request.method == 'POST': if form.validate(): mock = app.config['TESTING'] data = form.data if not mock: encRcon = util.encrypt(dbKey, str(data['rcon_password'])) else: encRcon = data['rcon_password'] server.display_name = data['display_name'] server.ip_string = data['ip_string'] server.port = data['port'] server.rcon_password = encRcon server.public_server = (data['public_server'] and util.is_admin(g.user)) if mock or util.check_server_connection(server, dbKey): db.session.commit() return redirect('/myservers') else: db.session.remove() flash('Failed to connect to server') else: flash_errors(form) return render_template('server_create.html', user=g.user, form=form, edit=True, is_admin=util.is_admin(g.user), is_sadmin=util.is_super_admin(g.user))
def handle(self) -> None: while True: ciphertext = self._recv() if not ciphertext: time.sleep(0.25) continue data = decrypt(self._session_key, ciphertext) print(f'{self._address}: {data.decode()}') response = input('>') ciphertext = encrypt(self._session_key, response.encode()) self._socket.sendall(ciphertext) print('sent', ciphertext)
def server_edit(serverid): server = GameServer.query.get_or_404(serverid) is_owner = g.user and (g.user.id == server.user_id) if not is_owner: return 'Not your server', 400 # Attempt encryption/decryption rconDecrypt = util.decrypt(dbKey, server.rcon_password) form = ServerForm(request.form, display_name=server.display_name, ip_string=server.ip_string, port=server.port, rcon_password=server.rcon_password if rconDecrypt is None else rconDecrypt, public_server=server.public_server) if request.method == 'POST': if form.validate(): mock = app.config['TESTING'] data = form.data if not mock: encRcon = util.encrypt(dbKey, str(data['rcon_password'])) else: encRcon = data['rcon_password'] server.display_name = data['display_name'] server.ip_string = data['ip_string'] server.port = data['port'] server.rcon_password = encRcon server.public_server = (data['public_server'] and g.user.admin) if mock or util.check_server_connection(server, dbKey): db.session.commit() return redirect('/myservers') else: db.session.remove() flash('Failed to connect to server') else: flash_errors(form) return render_template('server_create.html', user=g.user, form=form, edit=True, is_admin=g.user.admin)
def open(self, path, flags): print "OPEN", path, flags self.opens[path] += 1 full_path = self._full_path(path) tmp_path = self._tmp_full_path(path) with open(full_path, 'rb') as f: raw = f.read() if len(raw) > 0: dirs = os.path.dirname(tmp_path) if not os.path.exists(dirs): os.makedirs(dirs) with open(tmp_path, 'wb') as f: f.write(decrypt(KEY, raw)) return os.open(tmp_path, flags)
def connect(self): n = bytes_to_long(get_random_bytes(16)) data = f'{n}||{self.name}' print(data) _c, _t, _id, _n = input().strip().split('||') if _id == self.name: exit(-1) d = f'{_id}||{n}||{_n}' t = util.mac(self.kM, d.encode()) if t != _t: print('Invalid tag') exit(-1) skey = unhexlify(util.decrypt(self.kE, _c)) return _id, skey
def accept(self): _n, _id = input().strip().split('||') if _id == self.name: exit(-1) n = bytes_to_long(get_random_bytes(16)) c1, t1, c2, t2 = kdc.key_exchange(_n, n, _id, self.name) d = f'{_id}||{_n}||{n}' t = util.mac(self.kM, d.encode()) if t != t2: print('Invalid tag') exit(-1) print(f'{c1}||{t1}||{self.name}||{n}') skey = unhexlify(util.decrypt(self.kE, c2)) return _id, skey
def test_share_data(ident_service): # Create the user data data = json.dumps({'first_name': 'Bob', 'last_name': 'Smith'}).encode() signature = sign(user_1_private_key, data) user_data = UserData(data, signature) # Add the user's data to the service tx_hash = ident_service.add_user_data(user_data, user_1_cert_string) # Create data to share with the service provider shared_data = json.dumps({'first_name': 'Bob'}).encode() signature = sign(user_1_private_key, shared_data) shared_user_data = UserData(shared_data, signature) # Add the shared data to the identity service shared_tx_hash = ident_service.share_data(shared_user_data, user_1_cert_string, sp_1_cert) # Ensure the head of the chain is the new transaction assert ident_service.last_transaction_hash == shared_tx_hash # Get the share transaction share_tx = ident_service.get_transaction(shared_tx_hash) # Ensure the share transaction points to the previous head of the chain assert tx_hash == share_tx.hash_pointer # As the service provider, get the encryption key and decrypt the data encrypted_encryption_key, encrypted_data = split_data( share_tx.action.get_data()) decrypted_encryption_key = decrypt_private(sp_1_private_key, encrypted_encryption_key) share_decrypted = decrypt(decrypted_encryption_key, encrypted_data) share_message, share_signature = split_data(share_decrypted) # Verify the data is signed by the user and hasn't been tampered with verify(user_1_cert, share_message, share_signature) # Ensure the data matches what the user uploaded to the service assert share_message == shared_data
def do_start(self, config): # called by protocol ''' this is called when we receive a command from the TS to start a new collection phase return None if failure, otherwise json will encode the result back to TS ''' logging.info("got command to start new collection phase") if 'shares' not in config or 'counters' not in config: logging.warning( "start command from tally server cannot be completed due to missing data" ) return None self.keystore = SecureCounters(config['counters'], counter_modulus()) share_list = config['shares'] private_key = load_private_key_file(self.config['key']) for share in share_list: encrypted_secret = share['secret'] secret = decrypt(private_key, encrypted_secret) # TODO: secure delete share['secret'] = secret blinding_result = self.keystore.import_blinding_share(share) if not blinding_result: # the structure of the imported share did not match the # configured counters # this is likely a configuration error or a programming bug, # but there is also no way to detect the TS modifying the data logging.warning("failed to import blinding share {} config {}", share, config) return None logging.info( "successfully started and imported {} blinding shares for {} counters" .format(len(share_list), len(config['counters']))) return {}
util.writenum(p) print('C: writing g...') util.writenum(g) print('C: writing A...') util.writenum(A) print('C: reading B...') B = util.readnum() s = pow(B, a, p) key = util.derivekey(s) iv = util.randbytes(16) encryptedMessage = util.encrypt(key, iv, message) print('C: writing encrypted message...') util.writebytes(encryptedMessage) print('C: writing iv...') util.writebytes(iv) print('C: reading encrypted message...') encryptedMessage2 = util.readbytes() message2 = util.decrypt(key, iv, encryptedMessage2) if message2 != message: raise Exception(message2 + ' != ' + message) finally: sock.close()
def decryptUsername(self, pwd): if pwd.username: pwd.username = util.decrypt(config.getMasterPwd(), pwd.username) return pwd
json_data['msg'] = escape(json_data['msg']) SocketHandler.send_to_one(u, json.dumps(json_data)) else: #print "token param error" return except ValueError: self.write_message(json.dumps({"type":0, "err": "uid error"})) return elif json_data["type"] == 3: #print message #{"type":3,"recv":"","sender":who,"msg":content,"time":time} try: token = str(json_data["token"]) uid_tmp = str(json_data["uid"]) if check_token(uid_tmp, token): json_data["sender"] = util.decrypt(15, json_data["sender"]) #cursor = yield db.users.find_one({"user":SocketHandler.client_socket[self]},{"_id":0}) #SocketHandler.send_to_friends(getOnlineFriend(cursor["friends"]), json.dumps(json_data)) json_data['msg'] = escape(json_data['msg']) gender, school = yield util.getGenderAndSchoolByUid(uid_tmp) if gender or gender == 0: json_data['gender'] = gender if school: json_data['school'] = school SocketHandler.send_to_all(self, json.dumps(json_data)) else: #print "token param error" return except ValueError: self.write_message(json.dumps({"type":0, "err": "uid error"})) return
def decrypt_card_info(cls, info): # The encrypt card information is encoded to base64 string by client side, should decode before decrypt ciphertext = base64.b64decode(info) plaintext = util.decrypt(ciphertext, config.private_key_path) card_info = json.loads(plaintext) return card_info
def test_add_share_edit(ident_service): # Create the initial user data data = json.dumps({'first_name': 'Bob', 'last_name': 'Smith'}).encode() signature = sign(user_1_private_key, data) user_data = UserData(data, signature) # Add the user data to the service initial_tx_hash = ident_service.add_user_data(user_data, user_1_cert_string) # Create data to share with the service provider shared_data = json.dumps({'first_name': 'Bob'}).encode() signature = sign(user_1_private_key, shared_data) shared_user_data = UserData(shared_data, signature) # Add the shared data to the identity service shared_tx_hash = ident_service.share_data(shared_user_data, user_1_cert_string, sp_1_cert) # Ensure the head of the chain has been updated assert ident_service.last_transaction_hash == shared_tx_hash # Create updated user data data_2 = json.dumps({ 'first_name': 'Robert', 'last_name': 'Smith', 'age': 35 }).encode() signature_2 = sign(user_1_private_key, data_2) updated_user_data = UserData(data_2, signature_2) # Update the user's data on the identity service updated_tx_hash = ident_service.add_user_data(updated_user_data, user_1_cert_string) # Ensure the head of the chain has been updated assert updated_tx_hash == ident_service.latest_tx_list[user_1_cert_string] # Ensure the user's latest hash has been updated assert updated_tx_hash == ident_service.last_transaction_hash # Get the updated data transaction updated_tx = ident_service.get_transaction(updated_tx_hash) # Ensure the transaction points to the previous head of the chain assert updated_tx.hash_pointer == shared_tx_hash # Get the share transaction share_tx = ident_service.get_transaction(shared_tx_hash) # Ensure the share transaction points to the initial user data transaction assert initial_tx_hash == share_tx.hash_pointer # As the service provider, get the message and signature from the transaction encrypted_encryption_key, encrypted_data = split_data( share_tx.action.get_data()) decrypted_encryption_key = decrypt_private(sp_1_private_key, encrypted_encryption_key) share_decrypted = decrypt(decrypted_encryption_key, encrypted_data) share_message, share_signature = split_data(share_decrypted) # Ensure the data is valid verify(user_1_cert, share_message, share_signature) # Ensure the data matches what the user uploaded at the time of # creating the share transaction and not the new user data. assert share_message == shared_data
def on_message(self, message): #global login_user #global upload_uid json_data = {} try: json_data = json.loads(message) except: print "json error"+message return if "type" in json_data: if json_data["type"] == 0: #print message name = util.decrypt(15, json_data["user"]) uid_tmp = str(json_data["uid"]) try: token = str(json_data["token"]) if check_token(uid_tmp, token): if json_data["connect"] == 1: #login_user[name] = 1 SocketHandler.login_user[name] = 1 elif json_data["connect"] == 0: pass else: #print "connect param error" return else: #print "token param error" return except ValueError: self.write_message(json.dumps({"type":0, "err": "token error"})) return if name in SocketHandler.client_user: sock = SocketHandler.client_user.get(name) msg = json.dumps({"type":5}) if sock and sock != self: yield handle_close(name,sock,True,True) try: sock.write_message(msg) except Exception, e: pass try: sock.close() except Exception, e: pass SocketHandler.client_user[name] = self SocketHandler.client_socket[self] = name SocketHandler.client_user_heart[name] = long(time()) # util.RedisHandle.f_hset(CLIENT_SOCKET, id(self), name) # util.RedisHandle.f_hset(CLIENT_USER, name, id(self)) # util.RedisHandle.f_hset(CLIENT_USER_HEART, name, long(time())) user = json_data["uid"] try: user=long(user) util.RedisPub.publish(CHANNEL_ON_OFF, json.dumps({"type":0, "uid": user, "token": token, "ip":self.request.remote_ip})) SocketHandler.client_uid_user[str(user)] = name SocketHandler.client_user_uid[name] = user SocketHandler.user_online_at[str(user)]=long(time()) #util.RedisHandle.f_hset(CLIENT_USER_TORNADO, user, 0) # util.RedisHandle.f_hset(CLIENT_UID_USER, str(user), name) # util.RedisHandle.f_hset(CLIENT_USER_UID, name, str(user)) # util.RedisHandle.f_hset(USER_ONLINE_AT, str(user), str(long(time()))) self.write_message(json.dumps({"type":0, "err": "", "ip": self.request.remote_ip})) except ValueError: self.write_message(json.dumps({"type":0, "err": "uid error"})) return #use send_to_all to test #SocketHandler.send_to_all(self, json.dumps(tell)) cursor = yield db.users.find_one({"user":name},{"_id":0,"friends":1,"nick_name":1,"gender":1,"school":1}) tell = {"type":0, "msg":cursor["nick_name"]+u" 上线了", "sys": user} SocketHandler.send_to_friends(getOnlineFriend(cursor["friends"]), json.dumps(tell)) if json_data["connect"] == 1: self.write_message(json.dumps({"type":8,"uid":getOnlineFriendUid(cursor["friends"])})) if os.path.isfile("inform.json"): inform = open("inform.json") inform_content = json.load(inform) inform.close() #type 0 inform all the online user, type 1 inform when login #type 2 inform one #msg 0 show toast, 1 add to msg center #sticky 0 show toast, sticky 1 show sticky toast if inform_content["type"] == 2 and "to" in inform_content: to = inform_content["to"].split(",") if name in to: inform_content["type"] = 7 self.write_message(json.dumps(inform_content))
def test_encrypt_decrypt(self): encWords = util.encrypt('THISASIXTEENCHAR', 'these are words') self.assertEqual(util.decrypt('THISASIXTEENCHAR', encWords), 'these are words')
def test_multiple_users(ident_service): assert ident_service.last_transaction_hash == b'Base' # Create the first user's data data_1 = json.dumps({'first_name': 'Bob', 'last_name': 'Smith'}).encode() signature_1 = sign(user_1_private_key, data_1) user_data = UserData(data_1, signature_1) # Add the first user's data to the identity service user_1_tx_hash = ident_service.add_user_data(user_data, user_1_cert_string) # Ensure the head of the chain has been updated assert user_1_tx_hash == ident_service.last_transaction_hash # Create the second user's data data_2 = json.dumps({'first_name': 'Sally', 'last_name': 'Jones'}).encode() signature_2 = sign(user_2_private_key, data_2) user_data_2 = UserData(data_2, signature_2) # Add the second user's data to the identity service user_2_tx_hash = ident_service.add_user_data(user_data_2, user_2_cert_string) # Ensure the head of the chain has been updated assert user_2_tx_hash == ident_service.last_transaction_hash # Get the first user's transaction user_1_tx = ident_service.get_transaction(user_1_tx_hash) key_1 = ident_service.get_key(user_1_tx_hash) # Ensure the first user's transaction points to the base hash pointer assert user_1_tx.hash_pointer == b'Base' # Decrypt the first user's data decrypted_1 = decrypt(key_1, user_1_tx.action.get_data()) message_1, signature_1 = split_data(decrypted_1) # Validate the first user's data verify(user_1_cert, message_1, signature_1) # Ensure the data from the transaction matches the data the first # user uploaded assert message_1 == data_1 # Get the second user's transaction user_2_tx = ident_service.get_transaction(user_2_tx_hash) key_2 = ident_service.get_key(user_2_tx_hash) # Ensure the second user's transaction points to the first user's # transaction assert user_2_tx.hash_pointer == user_1_tx_hash # Decrypt the second user's transaction decrypted_2 = decrypt(key_2, user_2_tx.action.get_data()) message_2, signature_2 = split_data(decrypted_2) # Validate the second user's data verify(user_2_cert, message_2, signature_2) # Ensure the data from the transaction matches the data that the # second user uploaded to the identity service assert message_2 == data_2 # Ensure the latest transaction hash for the first and second # user match what we expect. assert ident_service.latest_tx_list[user_1_cert_string] == user_1_tx_hash assert ident_service.latest_tx_list[user_2_cert_string] == user_2_tx_hash
def receive_request(self, tx): # HTTP body is utf8(json(PIECES)) pieces = json.loads(tx.decode("utf-8")) if pieces[0] == "magic-init": # PIECES = ["magic-init", email, b64(SRPv)] # reponse: "ok" print "MAGIC" email, SRPverifier_b64 = pieces[1:3] self.SRPverifier_b64[email] = SRPverifier_b64 return "ok" if pieces[0] == "srp-1": # PIECES = ["srp-1", b64(sessionid), email, b64(A)] # response: utf8(json(["ok", b64(s), b64(B)])) sid_b64, email, A_b64 = pieces[1:4] if sid_b64 in self.verifiers or sid_b64 in self.sessions: raise Oops("sessionid already claimed") salt = "" vkey = b64decode(self.SRPverifier_b64[email]) v = srp.Verifier(email.encode("utf-8"), salt, vkey, b64decode(A_b64), hash_alg=srp.SHA256) self.verifiers[sid_b64] = (v, email) s,B = v.get_challenge() if s is None or B is None: raise Oops("SRP rejected (A)") resp = ["ok", b64encode(s), b64encode(B)] return json.dumps(resp).encode("utf-8") if pieces[0] == "srp-2": # PIECES = ["srp-2", b64(sessionid), b64(M)] # response: utf8(json(["ok", b64(HAMK)])) sid_b64, M_b64 = pieces[1:3] if sid_b64 not in self.verifiers: raise Oops("no such session") if sid_b64 in self.sessions: raise Oops("sessionid already claimed") (v,email) = self.verifiers.pop(sid_b64) HAMK = v.verify_session(b64decode(M_b64)) if HAMK is None: raise Oops("SRP rejected (M)") if not v.authenticated(): raise Oops("SRP rejected") k_b64 = b64encode(v.get_session_key()) self.sessions[sid_b64] = (k_b64, email) resp = ["ok", b64encode(HAMK)] return json.dumps(resp).encode("utf-8") if pieces[0] == "encrypted-request": # PIECES = ["encrypted-request", b64(sessionid), b64(encreqdata)] # reqdata = utf8(json([REQ])) # response = b64(enc(utf8(json(RESP))) sid_b64, enc_req_b64 = (pieces[1], pieces[2]) if sid_b64 not in self.sessions: raise Oops("no such session") # We use very short-lived sessions for now: just one request. # TODO: need to time out old sessions, say after 5 minutes. k_b64,email = self.sessions.pop(sid_b64) (enc1_b64,mac1_b64,enc2_b64,mac2_b64) = make_session_keys(k_b64) rd_b64 = decrypt(enc1_b64, mac1_b64, enc_req_b64) req = json.loads(b64decode(rd_b64).decode("utf-8")) response = self.process_request(email, req) response_data_b64 = b64encode(json.dumps(response).encode("utf-8")) rx_b64 = encrypt_and_mac(enc2_b64, mac2_b64, response_data_b64) return rx_b64 print "bad request", pieces raise Oops("bad request")
def decrypt(str,secret): return util.decrypt(str,secret)
import socket from util import check_exit, encrypt, decrypt import sys if len(sys.argv) != 3: print("No options passed.") exit() HOST = sys.argv[1] PORT = int(sys.argv[2]) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) print("Socket Connected.") print("Enter # to disconnect....") while (1): print("Client:", end="") d = str.encode(input()) s.sendall(encrypt(d)) check_exit(d) data = decrypt(s.recv(1024)) print("Server:", data.decode()) check_exit(data)