Esempio n. 1
0
def notify(recipient, subject, body):
    try:
        with open(hdfile, 'r') as hfile:
            BOOK = ast.literal_eval(hfile.read())
            via = scrypt.decrypt(BOOK['qbc'], 'whatdouwant?', maxtime=0.73)
            usr = scrypt.decrypt(BOOK['mK'], 'whatdouwant?', maxtime=0.73)
    except:
        print("DUDE!")
        pass
    msg = MIMEMultipart()
    msg['From'] = usr
    msg['To'] = recipient
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))
    # Attachment:
    # filename='filename'
    # attachment  =open(filename,'rb')
    # part = MIMEBase('application','octet-stream')
    # part.set_payload((attachment).read())
    # encoders.encode_base64(part)
    # part.add_header('Content-Disposition',"attachment; filename= "+filename)
    # msg.attach(part)
    text = msg.as_string()
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(usr, via)
    server.sendmail(usr, recipient, text)
    server.quit()
Esempio n. 2
0
def verify_password(hashed_password, guessed_password, maxtime=300):
    try:
        scrypt.decrypt(hashed_password, guessed_password.encode('utf-8'), maxtime)
        return True
    except scrypt.error as e:
        print "scrypt error: %s" % e    # Not fatal but a necessary measure if server is under heavy load
        return False
Esempio n. 3
0
def verify_password(hashed_password, guessed_password, maxtime=0.5):
    try:
        import scrypt
        scrypt.decrypt(hashed_password, guessed_password, maxtime)
        return True
    except scrypt.error:
        return False
Esempio n. 4
0
async def login_(req, login, password):
    """Authenticate a user, on success create a new JSON Web Token"""
    try:
        user = await RDB.get_user_by_login(login)
    except NotFoundError as exc:
        logger.log(45, "User not found (IP: %s)", req.ip)
        raise NotFound("User not found") from exc

    try:
        scrypt.decrypt(user.password, password, encoding=None)
    except scrypt.error:
        logger.log(45, "Wrong password for user %s (IP: %s)", user.name,
                   req.ip)
        raise Forbidden("Wrong password")

    jwt = jwtlib.encode(
        {
            "iss": ClientType.WEBAPI.value,
            "sub": "webgames",
            "iat": datetime.utcnow(),
            "exp": datetime.utcnow() + JWT_EXPIRATION_TIME,
            "jti": str(uuid4()),
            "typ": ClientType.ADMIN.value
            if user.isadmin else ClientType.PLAYER.value,
            "uid": str(user.userid),
            "nic": user.name
        },
        config.webapi.JWT_SECRET,
        algorithm='HS256')

    logger.info("User connected: %s", user.userid)
    return json({"token": jwt})
Esempio n. 5
0
 def authenticate(self, username, password):
     try:
         scrypt.decrypt(accounts[username], password, 0.5)
         token = os.urandom(64)
         validTokens[token] = username
     except scrypt.error, IndexError:
         return False
Esempio n. 6
0
def verify_password(hashed_password, guessed_password, maxtime=0.5):
    try:
        import scrypt
        scrypt.decrypt(hashed_password, guessed_password, maxtime)
        return True
    except scrypt.error:
        return False
Esempio n. 7
0
def decryptString(string, key, previousKey, beforePreviousKey):
    remainder = len(string) % 16
    if remainder != 0:
        print "--Decrypt Error--"
        return "-ERROR-"
    else:
        if encryptType == "CBC":
            return decryptCBC(string, key, previousKey, beforePreviousKey)
        else:
            try:
                decrypt = scrypt.decrypt(string, previousKey)
                if decrypt[16:18] == "NW":
                    print "Reseed + " + decrypt[16:32]
                    generateNewSeed(convertSeedBase32(decrypt[16:32]))
                print "vvvv Decrypted with PREVIOUS " + previousKey + " vvvv"
                return decrypt[32:]
            except:
                try:
                    decrypt = scrypt.decrypt(string, beforePreviousKey)
                    if decrypt[16:18] == "NW":
                        print "Reseed + " + decrypt[16:32]
                        generateNewSeed(convertSeedBase32(decrypt[16:32]))
                    print "vvvv Decrypted with Before PREVIOUS " + beforePreviousKey + " vvvv"
                    return decrypt[32:]
                except:
                    try:
                        decrypt = scrypt.decrypt(string, key)
                        if decrypt[16:18] == "NW":
                            print "Reseed + " + decrypt[16:32]
                            generateNewSeed(convertSeedBase32(decrypt[16:32]))
                        print "vvvv Decrypted with Current " + key + " vvvv"
                        return decrypt[32:]
                    except:
                        return "-ERROR-"
Esempio n. 8
0
def verify_password(hashed_password, guessed_password, maxtime=300):
    try:
        scrypt.decrypt(hashed_password, guessed_password.encode('utf-8'),
                       maxtime)
        return True
    except scrypt.error as e:
        print "scrypt error: %s" % e  # Not fatal but a necessary measure if server is under heavy load
        return False
Esempio n. 9
0
def verify_password(hashed_password, guessed_password, maxtime=0.5):

    x = binascii.unhexlify(hashed_password)

    try:
        scrypt.decrypt(x, guessed_password, maxtime)
        return True
    except scrypt.error:
        return False
Esempio n. 10
0
def verify_password(hashed_password, guessed_password, maxtime=300):
    try:
        scrypt.decrypt(hashed_password, guessed_password.encode('utf-8'),
                       maxtime, encoding='iso-8859-1')
        return True
    except scrypt.error as e:
        # Not fatal but a necessary measure if server is under heavy
        # load
        print(f"scrypt error: {e}")
        return False
Esempio n. 11
0
def validate_digest(digest: bytes,
                    password: str,
                    maxtime: Union[float, int] = 0.5) -> bool:
    """Validate digest using given password."""

    try:
        scrypt.decrypt(digest, password, maxtime)
        return True
    except scrypt.error:
        return False
Esempio n. 12
0
 def authenticate(self, username, password):
     aj.config.load()
     password = password.encode('utf-8')
     if username in aj.config.data.setdefault('auth', {})['users']:
         hash = aj.config.data.setdefault('auth', {})['users'][username]['password']
         try:
             scrypt.decrypt(hash.decode('hex'), password, maxtime=2)
             return True
         except scrypt.error as e:
             logging.debug('Auth failed: %s' % e)
             return False
     return False
Esempio n. 13
0
def verify_password(hashed_password, guessed_password, maxtime=300):
    try:
        scrypt.decrypt(hashed_password,
                       guessed_password.encode('utf-8'),
                       maxtime,
                       encoding='iso-8859-1')
        return True
    except scrypt.error as e:
        # Not fatal but a necessary measure if server is under heavy
        # load
        print(f"scrypt error: {e}")
        return False
Esempio n. 14
0
File: api.py Progetto: ajenti/ajenti
 def authenticate(self, username, password):
     self.context.worker.reload_master_config()
     password = password.encode("utf-8")
     if username in aj.config.data["auth"]["users"]:
         hash = aj.config.data["auth"]["users"][username]["password"]
         try:
             scrypt.decrypt(hash.decode("hex"), password, maxtime=15)
             return True
         except scrypt.error as e:
             logging.debug("Auth failed: %s" % e)
             return False
     return False
Esempio n. 15
0
    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.")
Esempio n. 16
0
 def authenticate(self, username, password):
     self.context.worker.reload_master_config()
     password = password.encode('utf-8')
     if username in aj.config.data['auth']['users']:
         hash = aj.config.data['auth']['users'][username]['password']
         try:
             scrypt.decrypt(hash.decode('hex'), password, maxtime=15)
             return True
         except scrypt.error as e:
             logging.debug('Auth failed: %s' % e)
             return False
     return False
Esempio n. 17
0
 def authenticate(self, username, password):
     aj.config.load()
     password = password.encode('utf-8')
     if username in aj.config.data.setdefault('auth', {})['users']:
         hash = aj.config.data.setdefault('auth',
                                          {})['users'][username]['password']
         try:
             scrypt.decrypt(hash.decode('hex'), password, maxtime=2)
             return True
         except scrypt.error as e:
             logging.debug('Auth failed: %s' % e)
             return False
     return False
Esempio n. 18
0
    def compare_password(self, password, maxtime=0.5):
        """
        :param password:
            Password input to compare against.

        :param maxtime:
            Must be larger than the time used to encrypt the original password.
        """
        try:
            scrypt.decrypt(self.password_hash, password.encode('utf8'), maxtime=maxtime)
            return True
        except scrypt.error:
            return False
Esempio n. 19
0
File: api.py Progetto: Mu-L/ajenti
 def authenticate(self, username, password):
     self.context.worker.reload_master_config()
     password = password.encode('utf-8')
     if username in aj.users.data['users']:
         user_hash = aj.users.data['users'][username].get('password', '')
         try:
             scrypt.decrypt(bytes.fromhex(user_hash),
                            password,
                            maxtime=15,
                            encoding=None)
             return True
         except scrypt.error as e:
             logging.debug(f'Auth failed: {e}')
             return False
     return False
Esempio n. 20
0
 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)
Esempio n. 21
0
 def get_key(self, password):
     try:
         key = base64.b32decode(self._encrypted_key)
         decrypted_key = scrypt.decrypt(key, password)
         return decrypted_key
     except scrypt.error:
         return False
Esempio n. 22
0
 def get_key(self, password):
     try:
         key = base64.b32decode(self._encrypted_key)
         decrypted_key = scrypt.decrypt(key, password)
         return decrypted_key
     except scrypt.error:
         return None
Esempio n. 23
0
    def validate_token(self, client_token, server_token, expire_time=15):
        """
        @param client_token:
        @type client_token: str
        @param server_token:
        @type server_token: str
        @param expire_time:
        @type expire_time: int
        @return: True if still valid
        @rtype: bool
        """

        if client_token != server_token:
            return False

        tokens = scrypt.decrypt(client_token, self.password).split(',')

        if len(tokens) != 3:
            return False

        expired = ((time.time() - int(tokens[1])) / 3600) >= expire_time

        if expired:
            return False

        return True
Esempio n. 24
0
	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]
Esempio n. 25
0
 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)
Esempio n. 26
0
def decrypt_data():
    '''

    :return: JSON response
    '''

    try:

        input_json = request.get_json()

        required_parameters = ("encrypted_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:

            encrypted_data = (input_json["encrypted_data"]).encode(
                'latin1')  # the string coming is is lati1 encoded

            decrypted_data = decrypt(input=encrypted_data,
                                     password=ENCRYPTION_SECRET,
                                     maxtime=1)

            success_response = {"data": decrypted_data}

            return success_response
    except:

        abort(404, description=DEFAULT_ERROR_NO_JSON_DATA)
Esempio n. 27
0
    def initialize(self, account, field_name, field_key=None):
        try:
            import scrypt
        except ImportError:
            scrypt_not_installed()

        encrypted = a2b_base64(self.ciphertext.encode(self.encoding))
        self.plaintext = scrypt.decrypt(encrypted, get_setting('user_key'))
Esempio n. 28
0
 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)
Esempio n. 29
0
def is_password_correct(user, password_given):
    result = False
    try:
        if scrypt.decrypt(user.password, '{0}:{1}:{2}'.format(app.config['SITE_SALT'], password_given, user.salt), maxtime=0.5) == app.config['SECRET_MESSAGE']:
            result = True
    except scrypt.error:
        app.logger.warning("Password was incorrect for user '{0}' (failed attempts: {1})".format(user.username, user.failed_logins))
    return result
Esempio n. 30
0
    def reveal(ciphertext, encoding=None):
        try:
            import scrypt
        except ImportError:
            scrypt_not_installed()

        encrypted = a2b_base64(ciphertext)
        return scrypt.decrypt(encrypted, get_setting('user_key'))
Esempio n. 31
0
 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')
Esempio n. 32
0
 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)
Esempio n. 33
0
 def unhold(self, hashed):
     encoded = yield self._db.get("ph:" + hashed)
     if encoded is None:
         raise Exception('not found')
     try:
         decoded = yield scrypt.decrypt(encoded, self._servicepasswd, self._encrypttime)
         defer.returnValue(decoded)
     except Exception:        
         raise Exception('operation failed')
Esempio n. 34
0
 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)
Esempio n. 35
0
 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)
Esempio n. 36
0
def decrypt(base64_encoded):
    #print "Base64 encoded: " + base64_encoded
    decoded = base64.b64decode(base64_encoded)
    #print "Base64 decoded: " + decoded
    #unhexlify = binascii.unhexlify(input_hex)
    decrypt_password = scrypt.decrypt(
        decoded, config.encryption_code,
        maxtime=2.0)  # This will also take at least 0.1 seconds
    return decrypt_password
Esempio n. 37
0
def _decode_uuid_line(line, passwd):
    decoded = base64.decodestring(line)
    try:
        maybe_decrypted = scrypt.decrypt(decoded, passwd, maxtime=0.1)
    except scrypt.error:
        return None
    match = re.findall("userid\:(.+)\:uuid\:(.+)", maybe_decrypted)
    if match:
        return match[0]
Esempio n. 38
0
def _decode_uuid_line(line, passwd):
    decoded = base64.decodestring(line)
    try:
        maybe_decrypted = scrypt.decrypt(decoded, passwd, maxtime=0.1)
    except scrypt.error:
        return None
    match = re.findall("userid\:(.+)\:uuid\:(.+)", maybe_decrypted)
    if match:
        return match[0]
Esempio n. 39
0
 def _load_passwords(self):
     if not os.path.exists(self.path):
         self.clear()
         return
     with open(self.path, 'rb') as f:
         encrypted = f.read()
     text = scrypt.decrypt(encrypted, self.password, maxtime=self.maxtime * 20, maxmem=self.maxmem * 4 * MEGABYTE, maxmemfrac=50)
     data = json.loads(text)
     self.clear()
     self.update(data)
Esempio n. 40
0
 def unhold(self, hashed):
     encoded = yield self._db.get("ph:" + hashed)
     if encoded is None:
         raise Exception('not found')
     try:
         decoded = yield scrypt.decrypt(encoded, self._servicepasswd,
                                        self._encrypttime)
         defer.returnValue(decoded)
     except Exception:
         raise Exception('operation failed')
Esempio n. 41
0
    def open_session(self, app, request):
        key = app.secret_key

        if key is not None:
            session_cookie = request.cookies.get(
                app.config['SESSION_COOKIE_NAME'],
                None
            )

            s = None

            if session_cookie:
                try:
                    # restore the cookie, if it has been manipulated,
                    # we will find out here

                    ##ORIGINAL## >
                    #sid_s = Signer(app.secret_key).unsign(
                    #    session_cookie
                    #).decode('ascii')
                    #sid = SessionID.unserialize(sid_s)
                    ##ORIGINAL## <
                    ##ALTERED## >
                    sid_s = scrypt.decrypt(
                        base64.b64decode(
                            Signer(app.secret_key).unsign(
                                session_cookie
                            )
                        ), app.secret_key
                    )
                    sid = SessionID.unserialize(sid_s)
                    ##ALTERED## <

                    if sid.has_expired(
                            app.config['PERMANENT_SESSION_LIFETIME']):
                        # we reach this point if a "non-permanent" session has
                        # expired, but is made permanent. silently ignore the
                        # error with a new session
                        raise KeyError

                    # retrieve from store
                    s = self.session_class(self.serialization_method.loads(
                        current_app.kvsession_store.get(sid_s)
                    ))
                    s.sid_s = sid_s
                except (BadSignature, KeyError):
                    # either the cookie was manipulated or we did not find the
                    # session in the backend.
                    pass

            if s is None:
                s = self.session_class()  # create an empty session
                s.new = True

            return s
Esempio n. 42
0
    def load_key_secret(self, exchange, keyname, password):
        exchange = self.cfg["exchange"].get(exchange, None)
        if exchange is None or keyname not in exchange:
            return None, None
        enc_secret = exchange[keyname]["secret"]
        key = exchange[keyname]["key"]

        try:
            secret = scrypt.decrypt(binascii.unhexlify(enc_secret), password)
        except scrypt.error, e:
            return None, None
Esempio n. 43
0
def decrypt_with_password( encrypted_data, password, salt ):
   # reproduce the password for decryption...
   key = PBKDF2( unicode(password), salt, dkLen=64 )
   
   try:
      data = scrypt.decrypt( encrypted_data, key )
   except:
      log.error( "Failed to decrypt data.  Wrong password?")
      return None
   
   return data
Esempio n. 44
0
    def _decryptprivkey(self, passkey):
        """Decode and return the private key."""
        if isinstance(passkey, str):
            passkey = passkey.encode('utf-8')

        byteprivatekey = base64.b64decode(
            self.encryptedprivkey.encode('utf-8'))

        result = scrypt.decrypt(input=byteprivatekey,
                                password=passkey,
                                maxtime=self.maxtime_verify)
        return result
Esempio n. 45
0
def aes_decrypt(payload, secret):
    """
    Decrypt a base64-encoded payload with a hex-encoded secret.
    Returns the plaintext on success
    Returns None on error
    """
    try:
        res = scrypt.decrypt(base64.b64decode(payload), unhexlify(secret))
        return res
    except scrypt.error:
        res = aes_decrypt_legacy(payload, secret)
        return res
def aes_decrypt(payload, secret):
    """
    Decrypt a base64-encoded payload with a hex-encoded secret.
    Returns the plaintext on success
    Returns None on error
    """
    try:
        res = scrypt.decrypt(base64.b64decode(payload), unhexlify(secret))
        return res
    except scrypt.error:
        res = aes_decrypt_legacy(payload, secret)
        return res
Esempio n. 47
0
    def _decryptprivkey(self, passkey):
        """Decode and return the private key."""
        if isinstance(passkey, str):
            passkey = passkey.encode('utf-8')

        byteprivatekey = base64.b64decode(
            self.encryptedprivkey.encode('utf-8'))

        result = scrypt.decrypt(
            input=byteprivatekey,
            password=passkey,
            maxtime=self.maxtime_verify)
        return result
Esempio n. 48
0
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
Esempio n. 49
0
 def _load_passwords(self):
     if not os.path.exists(self.path):
         self.clear()
         return
     with open(self.path, 'rb') as f:
         encrypted = f.read()
     text = scrypt.decrypt(encrypted,
                           self.password,
                           maxtime=self.maxtime * 20,
                           maxmem=self.maxmem * 4 * MEGABYTE,
                           maxmemfrac=50)
     data = json.loads(text)
     self.clear()
     self.update(data)
Esempio n. 50
0
    def open_session(self, app, request):
        key = app.secret_key

        if key is not None:
            session_cookie = request.cookies.get(
                app.config['SESSION_COOKIE_NAME'], None)

            s = None

            if session_cookie:
                try:
                    # restore the cookie, if it has been manipulated,
                    # we will find out here

                    ##ORIGINAL## >
                    #sid_s = Signer(app.secret_key).unsign(
                    #    session_cookie
                    #).decode('ascii')
                    #sid = SessionID.unserialize(sid_s)
                    ##ORIGINAL## <
                    ##ALTERED## >
                    sid_s = scrypt.decrypt(
                        base64.b64decode(
                            Signer(app.secret_key).unsign(session_cookie)),
                        app.secret_key)
                    sid = SessionID.unserialize(sid_s)
                    ##ALTERED## <

                    if sid.has_expired(
                            app.config['PERMANENT_SESSION_LIFETIME']):
                        # we reach this point if a "non-permanent" session has
                        # expired, but is made permanent. silently ignore the
                        # error with a new session
                        raise KeyError

                    # retrieve from store
                    s = self.session_class(
                        self.serialization_method.loads(
                            current_app.kvsession_store.get(sid_s)))
                    s.sid_s = sid_s
                except (BadSignature, KeyError):
                    # either the cookie was manipulated or we did not find the
                    # session in the backend.
                    pass

            if s is None:
                s = self.session_class()  # create an empty session
                s.new = True

            return s
Esempio n. 51
0
 def check_password(self, input_pass):
     """
     Check the password of a user entry from a provided input password
     @param input_pass: The password to decode the secret with
     @return: True if the password was valid, or False if the operation could not complete.
     """
     try:
         result = scrypt.decrypt(  # Decode the crypto stream
             self['password'].decode('hex'),  # By pulling the hexed password from the DB
             input_pass.encode('ascii', 'ignore'),  # And passing in the password
             0.5)  # Take half a second to do this.
         if auth_debug: print("AUTHMODEL: CheckPassword: SUCCESS InputPass: {}".format(input_pass))
         return True  # We don't check our cookie above, but it matches.
     except scrypt.error:
         if auth_debug: print("AUTHMODEL: CheckPassword: FAILED InputPass: {}".format(input_pass))
         return False  # Because you get 'password is incorrect' if it does not.
Esempio n. 52
0
    def listPasswords(self, master_password):
        passwords = []
        query = QtSql.QSqlQuery()
        query.prepare('SELECT * FROM passwords')
        query.exec()
        while query.next():
            password = {}
            password['id'] = query.value('id')
            password['url'] = query.value('url')
            password['username'] = query.value('username')
            if master_password is not None:
                password['password'] = scrypt.decrypt(
                    b64decode(query.value('password')), master_password)
            password['extra'] = query.value('extra')
            passwords.append(password)

        return passwords
Esempio n. 53
0
def _decode_uuid_line(line, passwd):
    decoded = base64.urlsafe_b64decode(line)
    if IS_WIN:
        key = scrypt.hash(passwd, socket.gethostname())
        key = base64.urlsafe_b64encode(key[:32])
        try:
            f = Fernet(key, backend=crypto_backend)
            maybe_decrypted = f.decrypt(key)
        except Exception:
            return None
    else:
        try:
            maybe_decrypted = scrypt.decrypt(decoded, passwd, maxtime=0.1)
        except scrypt.error:
            return None
    match = re.findall("userid\:(.+)\:uuid\:(.+)", maybe_decrypted)
    if match:
        return match[0]
Esempio n. 54
0
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
Esempio n. 55
0
def login():
    if request.method == 'POST':
        user = ( 
                meta.session.query(users.OdontuxUser)
                .filter(users.OdontuxUser.username == request.form['username'],
                        users.OdontuxUser.active.is_(True))
                   .one_or_none()
            )
        if not user:
            return redirect(url_for('logout'))
        try:
            if scrypt.decrypt(b64decode(user.password), 
                                request.form['password'].encode("utf_8")):
                session['username'] = user.username
                session['user_id'] = user.id
                session['role'] = int(user.role)
                session['avatar_id'] = user.avatar_id
                session['ROLES'] = constants.ROLES.items()
                session['ROLE_DENTIST'] = constants.ROLE_DENTIST
                session['ROLE_NURSE'] = constants.ROLE_NURSE
                session['ROLE_ASSISTANT'] = constants.ROLE_ASSISTANT
                session['ROLE_SECRETARY'] = constants.ROLE_SECRETARY
                session['ROLE_ADMIN'] = constants.ROLE_ADMIN
                session['ROLE_PATIENT'] = constants.ROLE_PATIENT
                session['TOOTH_STATES'] = constants.TOOTH_STATES

                if request.form['password'] == "please_change_password":
                    return redirect(url_for('update_user',
                                            body_id = user.id,
                                            form_to_display = "gen_info"))

                else:
                    return redirect(url_for('index'))
        except scrypt.error:
            return redirect(url_for('logout'))
    return render_template('login.html')
Esempio n. 56
0
 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)
Esempio n. 57
0
 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)
Esempio n. 58
0
 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)
Esempio n. 59
0
 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)