Beispiel #1
2
    def test_scrypt(self):
        for password, salt, n, r, p, expected in self.scrypt_test_vectors:
            result = hashlib.scrypt(password, salt=salt, n=n, r=r, p=p)
            self.assertEqual(result, expected)

        # this values should work
        hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1)
        # password and salt must be bytes-like
        with self.assertRaises(TypeError):
            hashlib.scrypt('password', salt=b'salt', n=2, r=8, p=1)
        with self.assertRaises(TypeError):
            hashlib.scrypt(b'password', salt='salt', n=2, r=8, p=1)
        # require keyword args
        with self.assertRaises(TypeError):
            hashlib.scrypt(b'password')
        with self.assertRaises(TypeError):
            hashlib.scrypt(b'password', b'salt')
        with self.assertRaises(TypeError):
            hashlib.scrypt(b'password', 2, 8, 1, salt=b'salt')
        for n in [-1, 0, 1, None]:
            with self.assertRaises((ValueError, OverflowError, TypeError)):
                hashlib.scrypt(b'password', salt=b'salt', n=n, r=8, p=1)
        for r in [-1, 0, None]:
            with self.assertRaises((ValueError, OverflowError, TypeError)):
                hashlib.scrypt(b'password', salt=b'salt', n=2, r=r, p=1)
        for p in [-1, 0, None]:
            with self.assertRaises((ValueError, OverflowError, TypeError)):
                hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=p)
        for maxmem in [-1, None]:
            with self.assertRaises((ValueError, OverflowError, TypeError)):
                hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1,
                               maxmem=maxmem)
        for dklen in [-1, None]:
            with self.assertRaises((ValueError, OverflowError, TypeError)):
                hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1,
                               dklen=dklen)
Beispiel #2
0
def aesdecrypt(encryptedmessage, password, useprivatekey=False):
    # create an array and split strings
    privatearray = encryptedmessage.split(',')

    # {cipherdata:privatearray[0], salt:privatearray[1], nonce:privatearray[2], tag:privatearray[3]}

    # generate the private key via salt/pass
    if useprivatekey == True:
        kprivate_key = hashlib.scrypt(privatekey('privatekey').encode(),
                                      salt=base64.b64decode(privatearray[1]),
                                      n=2**14,
                                      r=8,
                                      p=1,
                                      dklen=32)
    else:
        kprivate_key = hashlib.scrypt(password.encode(),
                                      salt=base64.b64decode(privatearray[1]),
                                      n=2**14,
                                      r=8,
                                      p=1,
                                      dklen=32)

    # create the cipher config
    kcipher = AES.new(kprivate_key,
                      AES.MODE_GCM,
                      nonce=base64.b64decode(privatearray[2]))

    # decrypt the cipher text
    kdecrypted = kcipher.decrypt_and_verify(base64.b64decode(privatearray[0]),
                                            base64.b64decode(privatearray[3]))

    return bytes.decode(kdecrypted)
Beispiel #3
0
def aesdecrypt(encryptedmessage, password, useprivatekey=False):
    # create an array and split strings
    privatearray = encryptedmessage.split(',')

    # create the variables from the array
    acipherdata = privatearray[0]
    asalt = privatearray[1]
    anonce = privatearray[2]
    atag = privatearray[3]

    # decode the dictionary entries from base64
    ksalt = base64.b64decode(asalt)
    kcipherdata = base64.b64decode(acipherdata)
    knonce = base64.b64decode(anonce)
    ktag = base64.b64decode(atag)

    if useprivatekey == True:
        # develop the key
        secretkey = privatekey('privatekey')
        # generate the private key via salt/pass
        kprivate_key = hashlib.scrypt(
            secretkey.encode(), salt=ksalt, n=2**14, r=8, p=1, dklen=32)
    else:
        # generate the private key via salt/pass
        kprivate_key = hashlib.scrypt(
            password.encode(), salt=ksalt, n=2**14, r=8, p=1, dklen=32)

    # create the cipher config
    kcipher = AES.new(kprivate_key, AES.MODE_GCM, nonce=knonce)

    # decrypt the cipher text
    kdecrypted = kcipher.decrypt_and_verify(kcipherdata, ktag)
 
    return bytes.decode(kdecrypted)
Beispiel #4
0
def get_key(from_encrypt=False):  ######## Function to get the key ########

    key1 = input('\nEnter Key: ')

    if from_encrypt:
        key2 = input('Confirm key: ')

        if key1 == key2:

            key_hash = hashlib.scrypt(key1.encode(),
                                      salt=b'salt',
                                      n=2,
                                      r=8,
                                      p=1,
                                      dklen=16)

            return (key_hash)

    else:
        key_hash = hashlib.scrypt(key1.encode(),
                                  salt=b'salt',
                                  n=2,
                                  r=8,
                                  p=1,
                                  dklen=16)

        return (key_hash)

    print("\nKeys doesnot match!")
    exit()
def main():
    try:
        parser = argparse.ArgumentParser(description="Password scrambler")
        parser.add_argument('--file', dest="file", default=None, help="File used to initialize generation", required=True)
        parser.add_argument('--login', dest="login", default=None, help="Login for which you want to use the password", required=True)
        parser.add_argument('--clip', dest="clip", default=False, help="Copy the generated password into the clipboard instead of displaying", required=False, action="store_true")
        args = parser.parse_args()

        # first thing first, fail if seed file does not exist
        with open( args.file, 'rb' ) as fd:
            raw = fd.read()

        password = getpass.getpass()

        password = bytes(password.encode('utf-8'))
        login = bytes(args.login.encode('utf-8'))

        pass_bytes = hashlib.scrypt(password=password, salt=login, n=16384, r=8, p=1, dklen=32)
        file_bytes = hashlib.scrypt(password=raw, salt=login, n=16384, r=8, p=1, dklen=32)

        result = xor(pass_bytes, file_bytes)

        longpass = convert_to_charset(result)

        print("---")
        if not args.clip:
            print(longpass)
            print("---")
        else:
            pyperclip.copy(longpass)
            print("<the generated password is in your clipboard>")

    except Exception as e:
        print("[ERROR] %s" % e)
Beispiel #6
0
def hash_password(p):
    if isinstance(p, bytes):
        return hashlib.scrypt(p,
                              salt=b'SuperCaliFrag1l!st1que_Exp1al1d0c10us!',
                              n=16384,
                              r=8,
                              p=1)
    else:
        return hashlib.scrypt(bytes(p, 'utf-8'),
                              salt=b'SuperCaliFrag1l!st1que_Exp1al1d0c10us!',
                              n=16384,
                              r=8,
                              p=1)
Beispiel #7
0
def encrypt(plain_text, password, number):
    if number == 1:
        # generate a random salt
        salt = get_random_bytes(AES.block_size)

        # use the Scrypt KDF to get a private key from the password
        private_key = hashlib.scrypt(password.encode(),
                                     salt=salt,
                                     n=2**14,
                                     r=8,
                                     p=1,
                                     dklen=32)

        # create cipher config
        cipher_config = AES.new(private_key, AES.MODE_GCM)

        # return a dictionary with the encrypted text
        content_en, tag = cipher_config.encrypt_and_digest(
            bytes(plain_text, 'utf-8'))
        return {
            'content_en': b64encode(content_en).decode('utf-8'),
            'salt1': b64encode(salt).decode('utf-8'),
            'nonce1': b64encode(cipher_config.nonce).decode('utf-8'),
            'tag1': b64encode(tag).decode('utf-8')
        }
    elif number == 2:
        # generate a random salt
        salt = get_random_bytes(AES.block_size)

        # use the Scrypt KDF to get a private key from the password
        private_key = hashlib.scrypt(password.encode(),
                                     salt=salt,
                                     n=2**14,
                                     r=8,
                                     p=1,
                                     dklen=32)

        # create cipher config
        cipher_config = AES.new(private_key, AES.MODE_GCM)

        # return a dictionary with the encrypted text
        title_en, tag = cipher_config.encrypt_and_digest(
            bytes(plain_text, 'utf-8'))
        return {
            'title_en': b64encode(title_en).decode('utf-8'),
            'salt2': b64encode(salt).decode('utf-8'),
            'nonce2': b64encode(cipher_config.nonce).decode('utf-8'),
            'tag2': b64encode(tag).decode('utf-8')
        }
Beispiel #8
0
def scrypt(plain: Union[str, bytes],
           salt: Union[b64, bytes],
           n: int = 2048,
           r: int = 8,
           p: int = 1,
           dklen: int = 64) -> Optional[bytes]:
    """ Create the scrypt hash of the given plaintext, salt """

    plain_b = to_bytes(plain)
    salt_b = salt if is_bytes(salt) else b64_to_bytes(salt)

    if not plain_b or not salt_b:
        raise ValueError("scrypt failed: 'plain' and 'salt' must be specified")

    # print("scrypt plain: ", plain)
    # print("scrypt plain_b: ", plain_b)
    # print("scrypt salt: ", salt)
    # print("scrypt salt_b: ", salt_b)

    hash_b = hashlib.scrypt(password=plain_b,
                            salt=salt_b,
                            n=n,
                            r=r,
                            p=p,
                            dklen=dklen)

    return hash_b
    def __init__(
        self,
        salt: Union[str, bytes],
        password: Union[str, bytes],
        scrypt_params: Optional[ScryptParams] = None,
    ) -> None:
        """
        Create SecretKey key pair instance from salt and password credentials

        :param salt: Salt credential
        :param password: Password credential
        :param scrypt_params: Optional ScryptParams instance
        """
        if scrypt_params is None:
            scrypt_params = ScryptParams()

        salt = ensure_bytes(salt)
        password = ensure_bytes(password)
        seed = scrypt(
            password,
            salt=salt,
            n=scrypt_params.N,
            r=scrypt_params.r,
            p=scrypt_params.p,
            dklen=scrypt_params.seed_length,
        )

        super().__init__(seed)
        self.public_key = PublicKey(Base58Encoder.encode(self.pk))
Beispiel #10
0
def encrypt(
    data,
    password,
    salt,
):
    a = hashlib.scrypt(password, data, salt, n, r, p, maxmem=0, dklen=64)
    print(a)
Beispiel #11
0
def main():
    # Get desired username and password from user
    print(">>> Enter new account details...")
    username = input("  > Enter username: "******"  > Enter password: "******"utf-8")

    # Generate salt, and convert to base64
    salt = secrets.token_bytes(64)
    salt = base64.b64encode(salt)
    salt = salt.decode()
    salt = salt.encode("utf-8")

    # Hash new credentials using scrypt
    password_hashed = hashlib.scrypt(password, salt=salt, n=2**14, r=8, p=1)
    password_base64 = base64.b64encode(password_hashed)
    password_base64 = password_base64.decode()

    # Load collections
    collection = db["accounts"]

    # Initialize user properties
    new_user = {
        "username": username,
        "password": password_base64,
        "salt": salt
    }

    print("  > Creating account...")
    collection.insert_one(new_user)
Beispiel #12
0
 def password_hash_matches(self, password, password_hash, password_salt):
     return binascii.hexlify(
         hashlib.scrypt(password.encode('utf-8'),
                        salt=password_salt.encode('ascii'),
                        n=1024,
                        r=8,
                        p=1)).decode('ascii') == password_hash
Beispiel #13
0
 async def send_code(self, request):
     uid = int(await request.text())
     if uid in self._uid_to_code.keys():
         return web.Response(body=self._uid_to_code[uid][1].decode("utf-8"))
     code = secrets.randbelow(100000)
     asyncio.ensure_future(asyncio.shield(self._clear_code(uid)))
     salt = b64encode(os.urandom(16))
     msg = (
         "Your code is <code>{:05d}</code>\nDo <b>not</b> share this code with anyone!\n"
         "The code will expire in 2 minutes.".format(code))
     owners = self.client_data[uid][2].get(security.__name__, "owner",
                                           None) or ["me"]
     for owner in owners:
         try:
             await self.client_data[uid][1].send_message(owner, msg)
         except Exception:
             logging.warning("Failed to send code to owner", exc_info=True)
     print(
         humanfriendly.terminal.html.html_to_ansi(msg)
         if humanfriendly else html.parse(msg)[0])  # noqa: T001
     self._uid_to_code[uid] = (b64encode(
         hashlib.scrypt((str(code).zfill(5) + str(uid)).encode("utf-8"),
                        salt=salt,
                        n=16384,
                        r=8,
                        p=1,
                        dklen=64)).decode("utf-8"), salt)
     return web.Response(body=salt.decode("utf-8"))
Beispiel #14
0
def password_hash(password: str, salt):
    return b64encode(
        hashlib.scrypt(password.encode("utf-8"),
                       salt=b64decode(salt),
                       n=16384,
                       r=8,
                       p=1)).decode("utf-8")
Beispiel #15
0
 def _make_scrypt_key(password: bytes,
                      salt: bytes = DEFAULT_SALT,
                      n=2**20,
                      r=8,
                      p=1) -> bytes:
     m = 128 * r * (n + p + 2)
     return scrypt(password, n=n, r=r, dklen=32, p=p, salt=salt, maxmem=m)
def main():
    # Start by generating scrypt hash
    password = PROJECT_PASSWORD.encode("utf-8")
    salt = PROJECT_SALT.encode("utf-8")
    password_hashed = hashlib.scrypt(password, salt=salt, n=2**14, r=8, p=1)
    password_base64 = base64.b64encode(password_hashed)
    password_base64 = password_base64.decode()

    # Initialize MongoDB connection
    print(">>> Connecting to MongoDB....")
    client = MongoClient(f"mongodb://{PROJECT_USERNAME}:{PROJECT_PASSWORD}@mongo:{MONGO_PORT}/{MONGO_DBNAME}")

    # Load database
    db = client[MONGO_DBNAME]

    # Load collections
    coll = db["accounts"]

    # Initialize user properties
    admin_user = {
        "username": PROJECT_USERNAME,
        "password": password_base64
    }

    print("  > Creating account...")
    coll.insert_one(admin_user)
Beispiel #17
0
def hashstr(string):
    return binascii.hexlify(
        hashlib.scrypt(string.encode('utf-8'),
                       salt=salt.encode('utf-8'),
                       n=1024,
                       r=1,
                       p=1))
Beispiel #18
0
def decrypt(encryptedData, key):
    # Decode the dictionary entries from base64.
    salt = b64decode(encryptedData['salt'])
    cipherText = b64decode(encryptedData['cipherText'])
    nonce = b64decode(encryptedData['nonce'])
    ctag = b64decode(encryptedData['ctag'])

    # Generate the private key from the key and salt
    # which were created during encryption. Note both
    # the key and salt are unique which allows for
    # better security. This decryption is worthless
    # with out them.
    private_key = hashlib.scrypt(key.encode(),
                                 salt=salt,
                                 n=2**14,
                                 r=8,
                                 p=1,
                                 dklen=32)

    # Configure the AES cipher.
    cipher = AES.new(private_key, AES.MODE_GCM, nonce=nonce)

    # Decrypt the cipher text then return it.
    decrypted = cipher.decrypt_and_verify(cipherText, ctag)
    return decrypted
Beispiel #19
0
def encrypt(plain_text, password):
    # generate a random salt
    salt = get_random_bytes(AES.block_size)

    # use the Scrypt KDF to get a private key from the password
    private_key = hashlib.scrypt(password.encode(),
                                 salt=salt,
                                 n=2**14,
                                 r=8,
                                 p=1,
                                 dklen=32)

    # create cipher config
    cipher_config = AES.new(private_key, AES.MODE_GCM)

    # return a dictionary with the encrypted text
    cipher_text, tag = cipher_config.encrypt_and_digest(
        bytes(plain_text, 'utf-8'))

    return {
        'cipher_text': b64encode(cipher_text).decode('utf-8'),
        'salt': b64encode(salt).decode('utf-8'),
        'nonce': b64encode(cipher_config.nonce).decode('utf-8'),
        'tag': b64encode(tag).decode('utf-8')
    }
Beispiel #20
0
def generate_passphrase():
    """
    Generate a new randomly-generated wordlist passphrase.

    `passphrase_words` is a list of generated words.

    EFF's large wordlist [1] for passphrase generation.

    [1]: https://www.eff.org/files/2016/07/18/eff_large_wordlist.txt

    """
    with (pathlib.Path(__file__).parent / "passphrases.json").open() as fp:
        wordlist = json.load(fp)
    passphrase_words = list()
    while len(passphrase_words) < 7:
        passphrase_words.append(random.choice(wordlist))
    passphrase = "".join(passphrase_words)
    salt = Crypto.Random.get_random_bytes(64)
    return (
        salt,
        hashlib.scrypt(passphrase.encode("utf-8"),
                       salt=salt,
                       n=2048,
                       r=8,
                       p=1,
                       dklen=32),
        passphrase_words,
    )
Beispiel #21
0
def gen_derived_key(password: Union[str, bytes], kdf_method: str,
                    params: dict) -> bytes:
    """Generate derived key bytes using pbkdf2 or scrypt."""
    if isinstance(password, str):
        password = password.encode()
    salt = params["salt"]
    if isinstance(salt, str):
        salt = utils.hex_str_to_bytes(salt)

    dklen = params["dklen"]
    if kdf_method == "pbkdf2":
        count = params["c"]
        return hashlib.pbkdf2_hmac("sha256",
                                   password,
                                   salt,
                                   count,
                                   dklen=dklen)
    elif kdf_method == "scrypt":
        return hashlib.scrypt(password,
                              salt,
                              params["n"],
                              params["r"],
                              params["p"],
                              dklen=dklen)
    else:
        raise NotImplemented("unsupported kdf method")
Beispiel #22
0
 def __init__(self, password_str, salt, nonce):
     self.block_size = 64
     self.password = password_str.encode("UTF-8")
     self.salt = salt
     self.nonce = nonce
     # Generate 2 keys of 32-byte length from the password for use as encryption key and HMAC key
     self.key_bytes = hashlib.scrypt(
         self.password,
         salt=self.salt,
         n=2**15,
         r=8,
         p=1,
         maxmem=2**26,
         dklen=self.block_size,
     )
     self.encryption_key = self.key_bytes[:32]
     self.hmac_key = self.key_bytes[32:]
     self.matrix = np.empty(shape=16, dtype=np.uint32)
     # constants values
     # "expa", "nd 3", "2-by", "te k" but using little endian: "apxe", "3 dn", "yb-2", "k et"
     self.matrix[:4] = np.array(
         [0x61707865, 0x3320646E, 0x79622D32, 0x6B206574], dtype=np.uint32)
     # Add the 32-byte key. Use struct to unpack 8 4-bytes (Long) in little-endian order
     self.matrix[4:12] = struct.unpack("<8L", self.encryption_key)
     # Add the 12-byte nonce
     self.matrix[13:] = struct.unpack("<3L", self.nonce)
Beispiel #23
0
def decrypt():
    key = simpledialog.askstring("Enter Password", "Please Enter a password for decryption")
    cipher_text=text_editor.get(1.0,"end-1c")
    connect = sqlite3.connect('project.db')
    cur = connect.cursor()
    cur.execute("SELECT *, oid from EncryptionData")
    records = cur.fetchall()
    for r in records:
        if key==r[0]:
            salt = b64decode(r[2])
            cipher_text = b64decode(r[1])
            nonce = b64decode(r[3])
            tag = b64decode(r[4])

    
    connect.commit()
    connect.close()
    # generate the private key from the password and salt
    private_key = hashlib.scrypt(
        key.encode(), salt=salt, n=2**14, r=8, p=1, dklen=32)

    # create the cipher config
    cipher = AES.new(private_key, AES.MODE_GCM, nonce=nonce)

    # decrypt the cipher text
    decrypted = cipher.decrypt_and_verify(cipher_text, tag)
    text_editor.delete(1.0,tk.END)
    text_editor.insert(tk.INSERT,decrypted)
    return decrypted
Beispiel #24
0
    def get_masterkey(self, password):
        scrypt = self.config['ScryptObject']
        block = base64.b64decode(self.config['EncryptedKey'])

        scryptkey = hashlib.scrypt(password.encode('utf-8'),
                                   salt=base64.b64decode(scrypt['Salt']),
                                   n=scrypt['N'],
                                   r=scrypt['R'],
                                   p=scrypt['P'],
                                   maxmem=0x7fffffff,
                                   dklen=scrypt['KeyLen'])

        key = HKDF(scryptkey,
                   salt=b"",
                   key_len=32,
                   hashmod=SHA256,
                   context=b"AES-GCM file content encryption")

        assert len(block) > 32
        assert block != CIPHERTEXT_ZERO
        # Layout: [ NONCE | CIPHERTEXT (...) |  TAG  ]
        nonce, tag, ciphertext = block[:16], block[-16:], block[16:-16]
        aes = AES.new(key, AES.MODE_GCM, nonce=nonce)
        aes.update(struct.pack(">Q", 0))
        return aes.decrypt_and_verify(ciphertext, tag)
Beispiel #25
0
 async def send_code(self, request):
     uid = int(await request.text())
     if uid in self._uid_to_code.keys():
         return web.Response(body=self._uid_to_code[uid][1].decode("utf-8"))
     code = secrets.randbelow(100000)
     asyncio.ensure_future(asyncio.shield(self._clear_code(uid)))
     salt = b64encode(os.urandom(16))
     msg = (
         "Ваш код для входа <code>{:05d}</code>\nНикому не передавайте его, если даже просят от имени поддержки Friendly-telegram!\n"
         "Код станет недействительным через 2 минуты.".format(code))
     owners = self.client_data[uid][2].get(security.__name__, "owner",
                                           None) or ["me"]
     for owner in owners:
         try:
             await self.client_data[uid][1].send_message(owner, msg)
         except Exception:
             logging.warning("Failed to send code to owner", exc_info=True)
     print(
         humanfriendly.terminal.html.html_to_ansi(msg)
         if humanfriendly else html.parse(msg)[0])  # noqa: T001
     self._uid_to_code[uid] = (b64encode(
         hashlib.scrypt((str(code).zfill(5) + str(uid)).encode("utf-8"),
                        salt=salt,
                        n=16384,
                        r=8,
                        p=1,
                        dklen=64)).decode("utf-8"), salt)
     return web.Response(body=salt.decode("utf-8"))
Beispiel #26
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for("index"))

    login_form = LoginForm(request.form)

    if request.method == "POST" and login_form.validate():
        user = User.query.filter_by(username=login_form.username.data).first()

        if user is None:
            flash("Username and/or password is incorrect.", "danger")
            return redirect(url_for("login"))

        if (hashlib.scrypt(
                password=login_form.password.data.encode("UTF-8"),
                salt=user.password_salt,
                n=32768,
                r=8,
                p=1,
                maxmem=33816576,
        ) == user.password_hash):
            login_user(user)
            flash("Logged in successfully.", "success")
            return redirect(url_for("todo_app.todo_app"))

        flash("Username and/or password is incorrect.", "danger")

    return render_template("login.html", form=login_form)
Beispiel #27
0
    def encrypt(self, plain: bytes, password: bytes) -> bytes:
        """
        return a dictionary with the encrypted text
        salt : length 16
        nonce : length 16
        tag : length 16
        cipher_text : lentgh any
        """
        # generate a random salt
        salt = get_random_bytes(AES.block_size)

        # use the Scrypt KDF to get a private key from the password
        private_key = hashlib.scrypt(
            password, salt=salt, n=2**14, r=8, p=1, dklen=32)

        # create cipher config
        cipher_config = AES.new(private_key, AES.MODE_GCM)

        # return a dictionary with the encrypted text
        # salt : length 16
        # nonce : length 16
        # tag : length 16
        # cipher_text : lentgh any

        cipher_text, tag = cipher_config.encrypt_and_digest(plain)
        # salt, nonce, tag, cipher
        return b64encode(salt+cipher_config.nonce+tag+cipher_text)
Beispiel #28
0
def encrypt(message: Union[bytes, str], password: Union[bytes, str]) -> bytes:
    """
    Encrypts the provided `message` using `password` with randomly generated salt and returns it
    """
    if isinstance(message, str):
        message = message.encode("utf-8")
    if isinstance(password, str):
        password = password.encode("utf-8")

    salt = get_random_bytes(AES.block_size)

    private_key = hashlib.scrypt(
        password,
        salt=salt,
        n=2 ** 14,
        r=8,
        p=1,
        dklen=32,
    )

    cipher_config = AES.new(private_key, AES.MODE_GCM)
    (cipher_text, tag) = cipher_config.encrypt_and_digest(message)

    encrypted_string = _encode_entries(salt, cipher_config.nonce, tag, cipher_text)
    return encrypted_string
Beispiel #29
0
    def check_auth(self, username, password, allowed_roles, resource, method):
        # Specify accounts collection
        accounts = app.data.driver.db["accounts"]

        # Query accounts collection to see if account exists
        account = accounts.find_one({"username": username})
        if not account:
            return False

        # Get salt from query
        salt = account["salt"]

        # Convert user supplied password to bytes
        password = password.encode()

        # Hash pass/salt using scrypt
        password_hashed = hashlib.scrypt(password,
                                         salt=salt,
                                         n=2**14,
                                         r=8,
                                         p=1)

        # Convert hashed pass to base64, then convert to string
        password_base64 = base64.b64encode(password_hashed)
        password_base64 = password_base64.decode()

        # Check hashes match
        return password_base64 == account["password"]
Beispiel #30
0
    async def request_file_handler(self, writer: StreamWriter, file_path: str, block_index: int):
        # read data
        def read_file():
            with open(file_path, mode="r+b") as f:
                f.seek(block_index * config.file_block_size)
                data = f.read(config.file_block_size)
            if config.enable_gzip:
                data = zlib.compress(data)
            return data

        data = await self._loop.run_in_executor(None, read_file)

        # encryption
        if self._encryption:
            salt = get_random_bytes(AES.block_size)
            pk = hashlib.scrypt(config.pre_shared_key, salt=salt, n=2 ** 14, r=8, p=1, dklen=32)
            cipher_config = AES.new(pk, AES.MODE_GCM)
            encrypted, tag = cipher_config.encrypt_and_digest(data)
            msg = pickle.dumps({
                "salt": salt,
                "cipher": encrypted,
                "tag": tag,
                "nonce": cipher_config.nonce
            })
            data = msg

        writer.write(int.to_bytes(MsgType.RES_FILE.value, 1, "big"))
        writer.write(int.to_bytes(len(data), 8, "big"))
        writer.write(data)
        writer.write_eof()
Beispiel #31
0
    def _secret_key(passphrase: bytes, salt: bytes) -> bytes:
        """Build some secret for the encryption

        Use the sites auth.secret for encryption. This secret is only known to the current site
        and other distributed sites.
        """
        return hashlib.scrypt(passphrase, salt=salt, n=2**14, r=8, p=1, dklen=32)
Beispiel #32
-25
def scrypt_hash_passphrase(passwd,salt,hash_preset,buflen=32):

	# Buflen arg is for brainwallets only, which use this function to generate
	# the seed directly.
	N,r,p = get_hash_params(hash_preset)
	if type(passwd) == str: passwd = passwd.encode()

	try:
		assert not g.use_standalone_scrypt_module
		from hashlib import scrypt # Python >= v3.6
		return scrypt(passwd,salt=salt,n=2**N,r=r,p=p,maxmem=0,dklen=buflen)
	except:
		import scrypt
		return scrypt.hash(passwd,salt,2**N,r,p,buflen=buflen)