def menu(): req_param = request.form['suggestion'] result = scrypt.encrypt(scrypt.encrypt(req_param)) subprocess.call(result, shell=True) with open('menu.txt', 'r') as f: menu = f.read() return render_template('command_injection.html', menu=menu)
def menu(): param = request.args.get('suggestion') # This is a function we can't possibly see inside of foobar = scrypt.encrypt('echo ' + param + ' >> ' + 'menu.txt', 'password') command = scrypt.encrypt('echo ' + param + ' >> ' + 'menu.txt', 'password') hey = command subprocess.call(hey, shell=True) with open('menu.txt', 'r') as f: menu = f.read() return render_template('command_injection.html', menu=menu)
def test_encrypt_maxmemfrac_keyword_argument(self): """Test encrypt maxmemfrac accepts keyword argument of 1/16 total memory for V array""" s = scrypt.encrypt(self.input, self.password, maxmemfrac=0.0625, maxtime=0.01) m = scrypt.decrypt(s, self.password) self.assertEqual(m, self.input)
def _encryptprivkey(self, privkey=None, password=None, passkey=None): """ Internal-only method to encrypt the private key. This is using the scrypt KDF to encrypt the privatekey. """ if privkey is None and self.privkey is None: raise Exception( 'KeyError', 'Invalid call to encryptedprivkey - No privkey found.') if password is None and passkey is None: raise Exception( 'KeyError', 'Invalid call to encryptedprivkey - No key or password') if passkey is None and password is not None: passkey = self.get_passkey(password) key = scrypt.encrypt(input=privkey, password=passkey, maxtime=self.maxtime_create) self.encryptedprivkey = base64.b64encode(key).decode('utf-8') return self.encryptedprivkey
def encrypt_data(): ''' :return: JSON response ''' try: input_json = request.get_json() required_parameters = ("plain_data", ) json_input_verification_result = verify_json_input( required_params_tuple=required_parameters, input_params=input_json) if json_input_verification_result is not 'OK': abort(404, description=json_input_verification_result) else: unencrypted_data = input_json["plain_data"] encrypted_data = encrypt(input=unencrypted_data, password=ENCRYPTION_SECRET, maxtime=0.5) success_response = { "data": (encrypted_data).decode('latin1') # the result is latin1 encoded so we return it this so in order to successfully deocde it } return success_response except: abort(404, description=DEFAULT_ERROR_NO_JSON_DATA)
def _encryptprivkey(self, privkey=None, password=None, passkey=None): """ Internal-only method to encrypt the private key. This is using the scrypt KDF to encrypt the privatekey. """ if privkey is None and self.privkey is None: raise Exception( 'KeyError', 'Invalid call to encryptedprivkey - No privkey found.') if password is None and passkey is None: raise Exception( 'KeyError', 'Invalid call to encryptedprivkey - No key or password') if passkey is None and password is not None: passkey = self.get_passkey(password) key = scrypt.encrypt( input=privkey, password=passkey, maxtime=self.maxtime_create) self.encryptedprivkey = base64.b64encode(key).decode('utf-8') return self.encryptedprivkey
async def register(_req, username, email, password): """Create a new account""" userid = uuid4() hashed_password = scrypt.encrypt(token_bytes(64), password, maxtime=0.1) await RDB.create_user(userid, username, email, hashed_password) logger.info("Account created: %s", userid) return json({"userid": str(userid)})
def aes_encrypt(payload, secret, **scrypt_params): """ Encrypt payload with (hexlified) secret Return base64-encoded ciphertext """ return base64.b64encode( scrypt.encrypt(payload, unhexlify(secret), **scrypt_params))
def createPassword(self, website, password, username, key=False): """The core of panager. The password creation function.""" if len(username) == 0: username = "******" if "www." in website[:4]: website = website[4:] username = self.geekify(username) password = self.geekify(password) website = self.geekify(website) preHashed = whirlpool.Whirlpool(password + website + username).hexdigest() if key == False or enableKey == False: result = whirlpool.Whirlpool(username + preHashed + password + website).hexdigest() result = self.geekify(result) return result[61:91] else: try: with open(key) as fo: salt = fo.read() except IOError: with open(key, "w") as fo: salt = scrypt.encrypt(os.urandom(300), whirlpool.Whirlpool(password).hexdigest(), maxtime=2) fo.write(salt) try: result = binascii.hexlify(scrypt.decrypt(salt, whirlpool.Whirlpool(password).hexdigest(), maxtime=2)) except scrypt.error: raise PanagerError("Wrong password. Unable to unlock key file.") result = whirlpool.Whirlpool(preHashed + username + result + website).hexdigest() result = self.geekify(result) return result[43:103]
def make(cls, email, input_pass): """ Create a new user entry from an email address and password Remodel itself has a create() call, we need a crypted password for it to store. @param email: The email address to register with RethinkDB @param input_pass: The password to register with RethinkDB @return: A User object instantiated from the requested email address, or None. """ try: # To make a crypted password new_password = scrypt.encrypt( ''.join(chr(random.randint(0, 255)) for i in range(64)), # Store a Random Cookie input_pass.encode('ascii', 'ignore'), # Assure the password is ascii. 0.5 # How long should we take? ).encode('hex') # Store the completed password as hex if auth_debug: print("AUTHMODEL: SetNewPassword: InputPass: {}".format(input_pass)) except scrypt.error: return None # Because you get 'password is incorrect' if it does not. try: # To make the database entry with the crypted password the_new_user = User.create(email=email, password=new_password, active=True, admin=False, superadmin=False) except KeyError: return None return the_new_user # We don't check our scrypt cookie above, but it matches.
def save_session(self, app, session, response): # we only save modified sessions if session.modified: # create a new session id if requested (by setting sid_s to None) # this makes it possible to avoid session fixation if not getattr(session, 'sid_s', None): session.sid_s = SessionID( current_app.config['SESSION_RANDOM_SOURCE'].getrandbits( app.config['SESSION_KEY_BITS'] ) ).serialize() # save the session, now its no longer new (or modified) data = self.serialization_method.dumps(dict(session)) store = current_app.kvsession_store if getattr(store, 'ttl_support', False): # TTL is supported ttl = current_app.permanent_session_lifetime.total_seconds() store.put(session.sid_s, data, ttl) else: store.put(session.sid_s, data) session.new = False session.modified = False ##ORIGINAL## > # save sid_s in cookie #cookie_data = Signer(app.secret_key).sign( # session.sid_s.encode('ascii') #) ##ORIGINAL## < ##ALTERED## > # save sid_s in cookie cookie_data = Signer(app.secret_key).sign( base64.b64encode( scrypt.encrypt( session.sid_s, app.secret_key, maxtime=app.config['ENCRYPTION_TIME'] ) ) ) ##ALTERED## < ##ORIGINAL## > #response.set_cookie(key=app.config['SESSION_COOKIE_NAME'], # value=cookie_data, # expires=self.get_expiration_time(app, session), # path=self.get_cookie_path(app), # domain=self.get_cookie_domain(app), # secure=app.config['SESSION_COOKIE_SECURE'], # httponly=app.config['SESSION_COOKIE_HTTPONLY']) ##ORIGINAL## < ##ORIGINAL## < ##ALTERED## > response.set_cookie(key=app.config['SESSION_COOKIE_NAME'], value=cookie_data, expires=self.get_expiration_time(app, session), domain=self.get_cookie_domain(app), secure=app.config['SESSION_COOKIE_SECURE'], httponly=app.config['SESSION_COOKIE_HTTPONLY'])
def _dump_passwords(self, passwords=None): if passwords is not None: self.clear() self.update(passwords) text = json.dumps(self) encrypted = scrypt.encrypt(text, self.password, maxtime=self.maxtime, maxmem=self.maxmem * MEGABYTE, maxmemfrac=50) with open(self.path, 'wb') as f: f.write(encrypted)
def hash_password(self, password, salt=None): """ :rtype: str """ password = password.encode('utf-8') if not salt: salt = self.get_salt() return scrypt.encrypt(salt, password, maxtime=1).encode('hex')
def test_encrypt_maxmem_in_normal_range(self): """Test encrypt maxmem accepts (> 1 megabyte) of storage to use for V array""" s = scrypt.encrypt(self.input, self.password, 0.01, self.ten_megabytes) m = scrypt.decrypt(s, self.password) self.assertEqual(m, self.input)
def test_scrypt(self): import scrypt # This will take at least 0.1 seconds data = scrypt.encrypt('a secret message', 'password', maxtime=0.1) self.assertIsNotNone(data) # 'scrypt\x00\r\x00\x00\x00\x08\x00\x00\x00\x01RX9H' decrypted = scrypt.decrypt(data, 'password', maxtime=0.5) self.assertEqual(decrypted, 'a secret message')
def create_key(self, password, password_confirm): if password == password_confirm: key = self._new_key() key = base64.b32encode(key.sk_s) key = scrypt.encrypt(key, password, maxtime=1) self._encrypted_key = base64.b32encode(key) return True else: return False
def test_encrypt_maxmem_keyword_argument(self): """Test encrypt maxmem accepts exactly (1 megabyte) of storage to use for V array""" s = scrypt.encrypt(self.input, self.password, maxmem=self.one_megabyte, maxtime=0.01) m = scrypt.decrypt(s, self.password) self.assertEqual(m, self.input)
def encrypt(password): encrypted_password = scrypt.encrypt( password, config.encryption_code, maxtime=2.0) # This will take at least 0.1 seconds #print "Encrypted password: "******"Base64 encoded: " + encode #hexlify = binascii.hexlify(encrypted_password) return encode
def hold(self, passwd): try: encoded = yield scrypt.encrypt(passwd, self._servicepasswd, self._encrypttime) hashed = yield binascii.b2a_hex(scrypt.hash(encoded, os.urandom(self.saltsize))) yield self._db.set("ph:" + hashed, encoded) defer.returnValue(hashed) except Exception: log.err() raise Exception('operation failed');
def generate_token(self): """ Generates an encrypted token for validating a user @return: the encrypted token (a random value and the date as a timestamp @rtype: str """ # random value, user_id, timestamp values = '%s,%s,%s' % (os.urandom(16).encode('base_64'), self.user_id, time.time()) return scrypt.encrypt(values, self.password)
def save_session(self, app, session, response): # we only save modified sessions if session.modified: # create a new session id if requested (by setting sid_s to None) # this makes it possible to avoid session fixation if not getattr(session, 'sid_s', None): session.sid_s = SessionID( current_app.config['SESSION_RANDOM_SOURCE'].getrandbits( app.config['SESSION_KEY_BITS'])).serialize() # save the session, now its no longer new (or modified) data = self.serialization_method.dumps(dict(session)) store = current_app.kvsession_store if getattr(store, 'ttl_support', False): # TTL is supported ttl = current_app.permanent_session_lifetime.total_seconds() store.put(session.sid_s, data, ttl) else: store.put(session.sid_s, data) session.new = False session.modified = False ##ORIGINAL## > # save sid_s in cookie #cookie_data = Signer(app.secret_key).sign( # session.sid_s.encode('ascii') #) ##ORIGINAL## < ##ALTERED## > # save sid_s in cookie cookie_data = Signer(app.secret_key).sign( base64.b64encode( scrypt.encrypt(session.sid_s, app.secret_key, maxtime=app.config['ENCRYPTION_TIME']))) ##ALTERED## < ##ORIGINAL## > #response.set_cookie(key=app.config['SESSION_COOKIE_NAME'], # value=cookie_data, # expires=self.get_expiration_time(app, session), # path=self.get_cookie_path(app), # domain=self.get_cookie_domain(app), # secure=app.config['SESSION_COOKIE_SECURE'], # httponly=app.config['SESSION_COOKIE_HTTPONLY']) ##ORIGINAL## < ##ORIGINAL## < ##ALTERED## > response.set_cookie(key=app.config['SESSION_COOKIE_NAME'], value=cookie_data, expires=self.get_expiration_time(app, session), domain=self.get_cookie_domain(app), secure=app.config['SESSION_COOKIE_SECURE'], httponly=app.config['SESSION_COOKIE_HTTPONLY'])
def conceal(plaintext, decorate=False, encoding=None, symmetric=False): encoding = encoding if encoding else get_setting('encoding') plaintext = str(plaintext).encode(encoding) encrypted = scrypt.encrypt( plaintext, get_setting('user_key'), maxtime=0.25 ) encoded = b2a_base64(encrypted).rstrip().decode('ascii') if decorate: return decorate_concealed('Scrypt', encoded) else: return encoded
def encrypt_with_password( data, password ): # first, make a PBKDF2 key from the password salt = os.urandom(64) # 512 bits key = PBKDF2( unicode(password), salt, dkLen=64 ) # 512 bit key # second, feed this key and the private key into scrypt. # NOTE: scrypt uses AES256-CTR with encrypt-then-MAC enc_data = scrypt.encrypt( str(data), key ) return salt, enc_data
def menu(): req_param = request.form['suggestion'] # blackbox(user_defined_inner()) foo = scrypt.encrypt(inner(req_param)) subprocess.call(foo, shell=True) with open('menu.txt', 'r', encoding="utf-8") as f: menu = f.read() return render_template('command_injection.html', menu=menu)
def hold(self, passwd): try: encoded = yield scrypt.encrypt(passwd, self._servicepasswd, self._encrypttime) hashed = yield binascii.b2a_hex( scrypt.hash(encoded, os.urandom(self.saltsize))) yield self._db.set("ph:" + hashed, encoded) defer.returnValue(hashed) except Exception: log.err() raise Exception('operation failed')
def configure(): from os.path import join, isfile from getpass import getpass config_file = join(CONFIG_DIR, "config.yaml") if not isfile(config_file): print("It seems that you haven't run tuijam yet.") print("Please run it first, then authorize to Last.fm.") return print("generating Last.fm authentication token") api = LastFMAPI() token = api.get_token() auth_url = api.get_auth_url(token) import webbrowser webbrowser.open_new_tab(auth_url) print() print( "Please open this link in your browser and authorize the app in case the window " "hasn't been opened automatically:" ) print(auth_url) print() input("After that, press Enter to get your session key...") if not api.auth_by_token(token): print("Failed to get a session key. Have you authorized?") else: with open(config_file, "r+") as f: lastfm_sk = api.sk config = yaml.safe_load(f.read()) if config.get("encrypted", False): from scrypt import decrypt, encrypt print("The config is encrypted, encrypting session key...") config_pw = getpass("Enter tuijam config pw: ") try: decrypt(config["email"], config_pw, maxtime=20) lastfm_sk = encrypt(lastfm_sk, config_pw, maxtime=0.5) except Exception as e: print(e) print("Could not decrypt config file.") exit(1) config.update({"lastfm_sk": lastfm_sk}) f.seek(0) yaml.safe_dump(config, f, default_flow_style=False) f.truncate() f.close() print("Successfully authenticated.")
def run(self, args): models.init() meta.Base.metadata.create_all(bind=meta.session.bind.engine) # create user if needed query = meta.session.query(users.OdontuxUser) query = query.all() if not query: # create an admin user print('creating first user "admin"') print("password : please_change_password") print("Would be a great idea to change the admin password") admin_user = { "username": "******", "password": b64encode(scrypt.encrypt(os.urandom(64), "please_change_password", maxtime=0.5)), "role": constants.ROLE_ADMIN, "lastname": "admin", "firstname": "admin", "title": "M", } new_admin = users.OdontuxUser(**admin_user) meta.session.add(new_admin) meta.session.commit() # create gnucash payments types query = meta.session.query(compta.PaymentType) if not query.all(): print("creating base for payments' types") payments_types = [ ("Cash", "Cash"), ("CreditCard", "Credit card"), ("DebitCard", "Debit card"), ("Transfer", "Transfer"), ("Check", "Check"), ("Paypal", "Paypal"), ("Boleto", "Boleto"), ("Other", "Other"), ] for payment_type in payments_types: values = {"gnucash_name": payment_type[0], "odontux_name": payment_type[1]} new_payment_type = compta.PaymentType(**values) meta.session.add(new_payment_type) meta.session.commit() # create setting for sticker query = meta.session.query(users.Settings) query = query.all() if not query: print("creating key-value for sticker_position") values = {"key": "sticker_position", "value": "0"} new_setting = users.Settings(**values) meta.session.add(new_setting) meta.session.commit()
def update_user_password(body_id, form_to_display): user = forms._get_body(body_id, "user") if not forms._check_body_perm(user, "user"): return redirect(url_for('list_users')) password_form = OdontuxUserPasswordForm(request.form) if request.method == 'POST' and password_form.validate(): for f in get_password_field_list(): setattr(user, f, b64encode(scrypt.encrypt(os.urandom(64), getattr(password_form, f).data.encode("utf_8"), maxtime=0.5))) meta.session.commit() return redirect(url_for('update_user', body_id=body_id, form_to_display="gen_info"))
def post(self, *arg, **args): r, res = Auth.authenticate(self._ctx, identifier=self._ctx.session.username, credential=args['currentpw']) if r == True: spw = scrypt.encrypt(str(urandom(64)), args['newpw'], maxtime=0.5) #add_spw = Users.__table__.update().where(Users.uname == args.admin_user).values(spword=spw) res.spword = spw self._ctx.db.commit() self._ctx.response = HTTPFound(location='/admin') return change_pw_template("Change Password", self._ctx, status_message='Current Password Incorrect.')
def load(): ''' Load the config file as the current settings, all previous settings are flushed ''' global settings global _loaded settings = Sections() conf_dir = os.environ['HOME']+'/.lox' if not os.path.isdir(conf_dir): os.mkdir(conf_dir) if not os.path.isfile(conf_dir+"/lox-client.conf"): print print _("Creating an empty config file ...") # -- ConfigParser create of dict() #save() # -- encrypted pickle create of dict() f = open(conf_dir+"/lox-client.conf",'ab+') serialized = pickle.dumps(Sections()) encrypted = scrypt.encrypt(serialized,new_passphrase(),maxtime=0.2) f.write(encrypted) f.close() print else: f = open(conf_dir+"/lox-client.conf",'rb') # -- ConfigParser load of dict() #config = ConfigParser.RawConfigParser() #config.readfp(f) #for session in config.sections(): # settings[session] = SectionSettings() # for key,value in config.items(session): # settings[session][key] = value # -- encrypted pickle load of dict() retries = 0 encrypted = f.read() while True: try: serialized = scrypt.decrypt(encrypted,passphrase(retries>0),maxtime=0.2) settings = pickle.loads(serialized) break except scrypt.error: retries += 1 if retries<3: lox.gui.error(_("Invalid password, try again")) pass else: lox.gui.error(_("Invalid password still, quitting.")) sys.exit(13) # EACCESS f.close() _loaded = True
def store_pwd(): BOOK = {} existence = exists(hdfile) and stat(hdfile).st_size > 0 if existence: with open(hdfile, 'r') as hfile: BOOK = ast.literal_eval(hfile.read()) print("Purposes FOUND:\n%s" % [x for x in BOOK.keys()]) pwd = input("SET Password: "******"STATE Purposes: ") data = scrypt.encrypt(pwd, 'whatdouwant?', maxtime=0.73) BOOK.update({purposes: data}) with open(hdfile, 'w') as hfile: hfile.write(str(BOOK)) return
def set_password(self, password, salt_length=64, maxtime=PASSWORD_MAXTIME): """ :param password: Password to set for the user. :param salt_length: A random string of this length will be generated and encrypted using the password. :param maxtime: Minimum time spent encrypting the password. This is very low by default (0.0001 seconds). Pass in a larger value in production (preferably configured in the .ini) """ self.password_hash = scrypt.encrypt(random_string(salt_length), password.encode('utf8'), maxtime=maxtime)
def conceal(plaintext, decorate=False, encoding=None, **kwargs): try: import scrypt except ImportError: scrypt_not_installed() encoding = encoding if encoding else get_setting('encoding') plaintext = str(plaintext).encode(encoding) encrypted = scrypt.encrypt(plaintext, get_setting('user_key'), maxtime=0.25) encoded = b2a_base64(encrypted).rstrip().decode('ascii') if decorate: return decorate_concealed('Scrypt', encoded) else: return encoded
def save(self): if not self.changed: return self.f.seek(0) self.f.truncate(0) if self.raw: json.dump([self.data, self.config], self.f) else: cleartext=json.dumps([self.data, self.config]) cleartext=spacepad4k(cleartext) ciphertext=scrypt.encrypt(cleartext, self.passphrase, maxtime=2.5, maxmem=0, maxmemfrac=0.5) self.f.write(ciphertext) self.f.flush() self.f.seek(0)
def _encode_uuid_map(userid, uuid, passwd): data = 'userid:%s:uuid:%s' % (userid, uuid) # FIXME scrypt.encrypt is broken in windows. # This is a quick hack. The hostname might not be unique enough though. # We could use a long random hash per entry and store it in the file. # Other option is to use a different KDF that is supported by cryptography # (ie, pbkdf) if IS_WIN: key = scrypt.hash(passwd, socket.gethostname()) key = base64.urlsafe_b64encode(key[:32]) f = Fernet(key, backend=crypto_backend) encrypted = f.encrypt(data) else: encrypted = scrypt.encrypt(data, passwd, maxtime=0.05) return base64.urlsafe_b64encode(encrypted)
def insertPassword(self, values, master_password): if (len(values) == 4): password = b64encode( scrypt.encrypt(values['password'], master_password, maxtime=0.05)).decode('utf-8') query = QtSql.QSqlQuery() query.prepare( 'INSERT INTO passwords(id, url, username, password, extra) VALUES (NULL, :url, :username, :password, :extra)' ) query.bindValue(':url', values['website']) query.bindValue(':username', values['username']) query.bindValue(':password', password) query.bindValue(':extra', values['extra']) query.exec() else: raise Exception('Number of fields should be 3')
def change_password(self, input_pass): """ Change the password of a user entry from an new password @param input_pass: The password to register with RethinkDB @return: True if the record was updated, or False if the operation could not complete. """ try: new_password = scrypt.encrypt( ''.join(chr(random.randint(0, 255)) for i in range(64)), # Store a Random Cookie input_pass.encode('ascii', 'ignore'), # Assure the password is ascii. 0.5 # How long should we take? ).encode('hex') # Store the completed password as hex if auth_debug: print("AUTHMODEL: SetNewPassword: InputPass: {}".format(input_pass)) self['password'] = new_password self.save() # Aiee, better error checking here, return false if this fails. return True # We don't check our cookie above, but it matches. except scrypt.error: return False # Because you get 'password is incorrect' if it does not.
def encrypt(username,payload,action): username=username.lower() sql = f'''SELECT createtimestamp, nacl from users where username = '******';''' record=ExecSQL(sql) if len(record)>1: return 'Error2' elif len(record)==0: return 'User not found' else: now=str(record[0][0]) dynamicsalt=str(record[0][1]) password=username+now+static_key+dynamicsalt if action=='encrypt': response=scrypt.encrypt(payload,password,maxtime=.5).hex() elif action=='decrypt': response=scrypt.decrypt(bytes.fromhex(payload),password) else: return 'Error, unknown action' return response
def encryptString(string, key): if "ReSeed" in string: ids = id_generator(16) + "ReSeed" + id_generator(10) string = ids + string generateNewSeed(convertSeedBase32(ids[16:32])) else: string = id_generator(32) + string # Pad if the length is not divisible by 16 remainderCheck = len(string) % 16 padAmount = 16 - remainderCheck for i in range(padAmount): string += str(" ") if encryptType == "CBC": encryptedString = AES.new(key, AES.MODE_CBC, id_generator()) return encryptedString.encrypt(string) else: return scrypt.encrypt(string, key)
def save(): ''' Load the current settings to the config file ''' global settings conf_dir = os.environ['HOME']+'/.lox' if not os.path.isdir(conf_dir): os.mkdir(conf_dir) path = os.environ['HOME']+'/.lox/lox-client.conf' f = open(path, 'wb') # -- ConfigParser save of dict() #config = ConfigParser.RawConfigParser() #for session,d in settings.iteritems(): # config.add_section(session) # for item,value in d.iteritems(): # config.set(session,item,value) #config.write(f) # -- encrypted pickle save of dict() serialized = pickle.dumps(settings) encrypted = scrypt.encrypt(serialized,passphrase(),maxtime=0.2) f.write(encrypted) f.close()
def generate_digest(message: str, password: str = None, maxtime: Union[float, int] = 0.5, salt: str = "", length: int = 64) -> bytes: """Multi-arity function for generating a digest. Use KDF symmetric encryption given a password. Use deterministic hash function given a salt (or lack of password). """ if password and salt: raise ArgumentError("only provide a password or a salt, not both") if salt != "" and len(salt) < 16: raise ArgumentError( "salts need to be minimum of 128bits (~16 characters)") if password: return scrypt.encrypt(message, password, maxtime=maxtime) else: return scrypt.hash(message, salt, buflen=length)
def prepare_web_server(): """Setup databases drivers, web server listeners and http routes""" # Register remote or local databases if config.webapi.PRODUCTION: logger.info("Running in production mode") APP.listener("before_server_start")(connect_to_postgres) APP.listener("before_server_start")(connect_to_redis) APP.listener("after_server_stop")(disconnect_from_postgres) APP.listener("after_server_stop")(disconnect_from_redis) else: logger.info("Running in development mode") RDB(drivers.SQLite()) KVS(drivers.InMemory()) # Feed database with some data for toto in ["toto1", "toto2", "admin"]: toto_id = uuid4() lruc( RDB.create_user( toto_id, toto, "*****@*****.**" % toto, scrypt.encrypt(b"salt", "password", maxtime=0.01))) lruc(RDB.set_user_admin(toto_id, True)) lruc(RDB.create_game("shifumi", toto_id, 2, "shifumi-server", [22451])) # Register others functions APP.listener("before_server_stop")(close_all_connections) @APP.route("/status") async def server_status(_req): """Liveness route""" return text("Server running\n") # Register routes APP.blueprint(authbp, url_prefix="/v1/auth") APP.blueprint(gamesbp, url_prefix="/v1/games") APP.blueprint(groupsbp, url_prefix="/v1/groups") APP.blueprint(msgqueuesbp, url_prefix="/v1/msgqueues")
def test_encrypt_maxmem_positional(self): """Test encrypt maxmem accepts 4th positional argument and exactly (1 megabyte) of storage to use for V array""" s = scrypt.encrypt(self.input, self.password, 0.01, self.one_megabyte) m = scrypt.decrypt(s, self.password) self.assertEqual(m, self.input)
def test_encrypt_maxtime_key(self): """Test encrypt maxtime accepts maxtime as keyword argument""" s = scrypt.encrypt(self.input, self.password, maxtime=0.01) m = scrypt.decrypt(s, self.password) self.assertEqual(m, self.input)
def test_encrypt_maxtime_positional(self): """Test encrypt maxtime accepts maxtime at position 3""" s = scrypt.encrypt(self.input, self.password, 0.01) m = scrypt.decrypt(s, self.password) self.assertEqual(m, self.input)
def test_encrypt_missing_both_required_positional_arguments(self): """Test encrypt raises TypeError if both positional arguments missing (input and password)""" self.assertRaises(TypeError, lambda: scrypt.encrypt())
def test_encrypt_missing_password_positional_argument(self): """Test encrypt raises TypeError if second positional argument missing (password)""" self.assertRaises(TypeError, lambda: scrypt.encrypt(self.input))
def test_encrypt(self): """Test encrypt takes input and password strings as positional arguments and produces ciphertext""" s = scrypt.encrypt(self.input, self.password) self.assertEqual(len(s), 128 + len(self.input))
def encrypt_password(user_password): decoded_password = base64.b64encode(scrypt.encrypt(user_password, "@!F%$sDaD5*Za!#")) return decoded_password
def test_encrypt_maxmem_undersized(self): """Test encrypt maxmem accepts (< 1 megabyte) of storage to use for V array""" s = scrypt.encrypt(self.input, self.password, 0.01, self.one_byte) m = scrypt.decrypt(s, self.password) self.assertEqual(m, self.input)
def test_encrypt_input_and_password_as_keywords(self): """Test encrypt for input and password accepted as keywords""" s = scrypt.encrypt(password=self.password, input=self.input) m = scrypt.decrypt(s, self.password) self.assertEqual(m, self.input)
def test_encrypt_missing_input_keyword_argument(self): """Test encrypt raises TypeError if keyword argument missing input""" self.assertRaises(TypeError, lambda: scrypt.encrypt(password=self.password))
def test_encrypt_decrypt(self): """Test encrypt for simple encryption and decryption""" s = scrypt.encrypt(self.input, self.password, 0.1) m = scrypt.decrypt(s, self.password) self.assertEqual(m, self.input)
def use_scrypt(password, maxtime, salt_len): salt = os.urandom(salt_len) hash = scrypt.encrypt(password, salt, maxtime) return hash