Exemplo n.º 1
0
    def _set_client_secret(self, client_secret):
        if self._salt:
            salt = b64decode(self._salt.encode('utf-8'))
        else:
            try:
                if not oauth2_settings('salt'):
                    raise ValueError(
                        'oauth2_provider.salt configuration required.'
                    )
                salt = b64decode(oauth2_settings('salt').encode('utf-8'))
            except AttributeError:
                return

        kdf = Scrypt(
            salt=salt,
            length=64,
            n=2 ** 14,
            r=8,
            p=1,
            backend=backend
        )

        try:
            client_secret = bytes(client_secret, 'utf-8')
        except TypeError:
            pass
        self._client_secret = kdf.derive(client_secret)
 def hash(password, salt):
     kdf = Scrypt(salt=salt,
                  length=SCRYPT_LEN,
                  n=SCRYPT_N,
                  r=SCRYPT_R,
                  p=SCRYPT_P,
                  backend=default_backend())
     return kdf.derive(password.encode('utf-8'))
Exemplo n.º 3
0
    def test_verify(self, backend, params):
        password = params["password"]
        work_factor = int(params["n"])
        block_size = int(params["r"])
        parallelization_factor = int(params["p"])
        length = int(params["length"])
        salt = params["salt"]
        derived_key = params["derived_key"]

        scrypt = Scrypt(salt, length, work_factor, block_size, parallelization_factor, backend)
        assert scrypt.verify(password, binascii.unhexlify(derived_key)) is None
Exemplo n.º 4
0
    def test_already_finalized(self, backend):
        password = b"password"
        work_factor = 1024
        block_size = 8
        parallelization_factor = 16
        length = 64
        salt = b"NaCl"

        scrypt = Scrypt(salt, length, work_factor, block_size, parallelization_factor, backend)
        scrypt.derive(password)
        with pytest.raises(AlreadyFinalized):
            scrypt.derive(password)
Exemplo n.º 5
0
    def test_buffer_protocol(self, backend):
        password = bytearray(b"password")
        work_factor = 256
        block_size = 8
        parallelization_factor = 16
        length = 10
        salt = b"NaCl"

        scrypt = Scrypt(salt, length, work_factor, block_size,
                        parallelization_factor, backend)

        assert scrypt.derive(password) == b'\xf4\x92\x86\xb2\x06\x0c\x848W\x87'
Exemplo n.º 6
0
    def test_password_not_bytes(self, backend):
        password = 1
        work_factor = 1024
        block_size = 8
        parallelization_factor = 16
        length = 64
        salt = b"NaCl"

        scrypt = Scrypt(salt, length, work_factor, block_size, parallelization_factor, backend)

        with pytest.raises(TypeError):
            scrypt.derive(password)
Exemplo n.º 7
0
    def test_invalid_verify(self, backend):
        password = b"password"
        work_factor = 1024
        block_size = 8
        parallelization_factor = 16
        length = 64
        salt = b"NaCl"
        derived_key = b"fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e773"

        scrypt = Scrypt(salt, length, work_factor, block_size, parallelization_factor, backend)

        with pytest.raises(InvalidKey):
            scrypt.verify(password, binascii.unhexlify(derived_key))
Exemplo n.º 8
0
    def test_derive(self, backend, params):
        _skip_if_memory_limited(_MEM_LIMIT, params)
        password = params["password"]
        work_factor = int(params["n"])
        block_size = int(params["r"])
        parallelization_factor = int(params["p"])
        length = int(params["length"])
        salt = params["salt"]
        derived_key = params["derived_key"]

        scrypt = Scrypt(salt, length, work_factor, block_size,
                        parallelization_factor, backend)
        assert binascii.hexlify(scrypt.derive(password)) == derived_key
Exemplo n.º 9
0
    def test_scrypt_malloc_failure(self, backend):
        password = b"NaCl"
        work_factor = 1024 ** 3
        block_size = 589824
        parallelization_factor = 16
        length = 64
        salt = b"NaCl"

        scrypt = Scrypt(salt, length, work_factor, block_size,
                        parallelization_factor, backend)

        with pytest.raises(MemoryError):
            scrypt.derive(password)
Exemplo n.º 10
0
def oauth2_token(request):
    """
    * In the case of an incoming authentication request a POST is made
    with the following structure.

        POST /token HTTP/1.1
        Host: server.example.com
        Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
        Content-Type: application/x-www-form-urlencoded

        grant_type=password&username=johndoe&password=A3ddj3w

    The basic auth header contains the client_id:client_secret base64
    encoded for client authentication.

    The username and password are form encoded as part of the body. This
    request *must* be made over https.

    The response to this request will be, assuming no error:

        HTTP/1.1 200 OK
        Content-Type: application/json;charset=UTF-8
        Cache-Control: no-store
        Pragma: no-cache

        {
          "access_token":"2YotnFZFEjr1zCsicMWpAA",
          "token_type":"bearer",
          "expires_in":3600,
          "refresh_token":"tGzv3JOkF0XG5Qx2TlKW",
          "user_id":1234,
        }

    * In the case of a token refresh request a POST with the following
    structure is required:

        POST /token HTTP/1.1
        Host: server.example.com
        Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
        Content-Type: application/x-www-form-urlencoded

        grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKW&user_id=1234

    The response will be the same as above with a new access_token and
    refresh_token.
    """

    # Make sure this is a POST.
    if request.method != 'POST':
        log.info('rejected request due to invalid method: %s' % request.method)
        return HTTPMethodNotAllowed(
            'This endpoint only supports the POST method.')

    getClientCredentials(request)

    # Make sure we got a client_id and secret through the authorization
    # policy. Note that you should only get here if not using the Oauth2
    # authorization policy or access was granted through the AuthTKt policy.
    if (not hasattr(request, 'client_id') or
        not hasattr(request, 'client_secret')):
        log.info('did not receive client credentials')
        return HTTPUnauthorized('Invalid client credentials')

    client = db.query(Oauth2Client).filter_by(
        client_id=request.client_id).first()

    # Again, the authorization policy should catch this, but check again.
    if not oauth2_settings('salt'):
        raise ValueError('oauth2_provider.salt configuration required.')
    salt = b64decode(oauth2_settings('salt').encode('utf-8'))
    kdf = Scrypt(
        salt=salt,
        length=64,
        n=2 ** 14,
        r=8,
        p=1,
        backend=backend
    )

    try:
        client_secret = request.client_secret
        try:
            client_secret = bytes(client_secret, 'utf-8')
        except TypeError:
            client_secret = client_secret.encode('utf-8')
        kdf.verify(client_secret, client.client_secret)
        bad_secret = False
    except (AttributeError, InvalidKey):
        bad_secret = True
    if not client or bad_secret:
        log.info('received invalid client credentials')
        return HTTPBadRequest(InvalidRequest(
            error_description='Invalid client credentials'))

    # Check for supported grant type. This is a required field of the form
    # submission.
    resp = None
    grant_type = request.POST.get('grant_type')
    if grant_type == 'password':
        resp = handle_password(request, client)
    elif grant_type == 'refresh_token':
        resp = handle_refresh_token(request, client)
    else:
        log.info('invalid grant type: %s' % grant_type)
        return HTTPBadRequest(UnsupportedGrantType(error_description='Only '
            'password and refresh_token grant types are supported by this '
            'authentication server'))

    add_cache_headers(request)
    return resp
Exemplo n.º 11
0
def main():
    parser = argparse.ArgumentParser(description="Decrypt an Aegis vault")
    parser.add_argument("--input",
                        dest="input",
                        required=True,
                        help="encrypted Aegis vault file")
    parser.add_argument("--output",
                        dest="output",
                        default="-",
                        help="output file ('-' for stdout)")
    args = parser.parse_args()

    # parse the Aegis vault file
    with io.open(args.input, "r") as f:
        data = json.load(f)

    # ask the user for a password
    password = getpass.getpass().encode("utf-8")

    # extract all password slots from the header
    header = data["header"]
    slots = [slot for slot in header["slots"] if slot["type"] == 1]

    # try the given password on every slot until one succeeds
    master_key = None
    for slot in slots:
        # derive a key from the given password
        kdf = Scrypt(salt=bytes.fromhex(slot["salt"]),
                     length=32,
                     n=slot["n"],
                     r=slot["r"],
                     p=slot["p"],
                     backend=backend)
        key = kdf.derive(password)

        # try to use the derived key to decrypt the master key
        cipher = AESGCM(key)
        params = slot["key_params"]
        try:
            master_key = cipher.decrypt(nonce=bytes.fromhex(params["nonce"]),
                                        data=bytes.fromhex(slot["key"]) +
                                        bytes.fromhex(params["tag"]),
                                        associated_data=None)
            break
        except cryptography.exceptions.InvalidTag:
            pass

    if master_key is None:
        die("error: unable to decrypt the master key with the given password")

    # decode the base64 vault contents
    content = base64.b64decode(data["db"])

    # decrypt the vault contents using the master key
    params = header["params"]
    cipher = AESGCM(master_key)
    db = cipher.decrypt(nonce=bytes.fromhex(params["nonce"]),
                        data=content + bytes.fromhex(params["tag"]),
                        associated_data=None)

    db = db.decode("utf-8")
    if args.output != "-":
        with io.open(args.output, "w") as f:
            f.write(db)
    else:
        print(db)
Exemplo n.º 12
0
    def addFolderKek(self, folder_path):
        #set folder password which allows user to gain access to shared_folder
        folder_pwd = input("Set folder password used for first access: ")

        #store hash of folder password to verify that entered password is the correct one later (needed on first access to folder)
        salt = os.urandom(16)
        kdf = Scrypt(salt=salt,
                     length=32,
                     n=2**4,
                     r=8,
                     p=1,
                     backend=default_backend())
        key = kdf.derive(folder_pwd.encode())
        self.pwd_db.update({folder_path: key})

        #generate kek of folder
        generated_kek = Fernet.generate_key()

        #encrypt the kek using the folder password and store the encrypted kek
        kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),
                         length=32,
                         salt=salt,
                         iterations=100000,
                         backend=default_backend())
        folder_key = kdf.derive(folder_pwd.encode())
        f = Fernet(urlsafe_b64encode(folder_key))
        folder_kek = f.encrypt(generated_kek)
        self.kek_db.update({
            folder_path: {
                "decryption_kek": folder_kek,
                "encryption_kek": folder_kek,
                "salt": salt,
                "rotate": False
            }
        })

        while True:
            user_pwd = input("Enter your user password: "******"salt"],
                         length=32,
                         n=2**4,
                         r=8,
                         p=1,
                         backend=default_backend())
            try:
                kdf.verify(user_pwd.encode(),
                           self.users[self.currentUser]["pwd"])
            except InvalidKey:
                print("The password is wrong.")
                continue
            else:
                break

        #store folder password which was encrypted using user password
        kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),
                         length=32,
                         salt=self.users[self.currentUser]["salt"],
                         iterations=100000,
                         backend=default_backend())
        user_key = kdf.derive(user_pwd.encode())
        f = Fernet(urlsafe_b64encode(user_key))
        encrypted_folder_pwd = f.encrypt(folder_pwd.encode())
        self.users[self.currentUser]["folders"].update(
            {folder_path: encrypted_folder_pwd})
Exemplo n.º 13
0
    def addDek(self, file_name, dek, tag, iv):
        #get folder path by eliminating filename from file path contained in <file_name>
        folder_path = "/".join(file_name.split("/")[0:-1])
        name = file_name.split("/")[-1]
        print(name)

        #user has to input user password until the hash of it is equal to the stored user password hash (until the password is correct)
        while True:
            pwd = input("user  password: "******"salt"],
                         length=32,
                         n=2**4,
                         r=8,
                         p=1,
                         backend=default_backend())
            try:
                kdf.verify(pwd.encode(), self.users[self.currentUser]["pwd"])
            except InvalidKey:
                print("The password is wrong.")
                continue
            else:
                break

        #get encrypted folder password and encrypted kek
        encrypted_folder_pwd = self.users[
            self.currentUser]["folders"][folder_path]
        stored_kek = self.getEncryptionFolderKek(folder_path)

        #decrypt folder password using the user password
        kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),
                         length=32,
                         salt=self.users[self.currentUser]["salt"],
                         iterations=100000,
                         backend=default_backend())
        pwd_key = kdf.derive(pwd.encode())

        f = Fernet(urlsafe_b64encode(pwd_key))
        folder_pwd = f.decrypt(encrypted_folder_pwd)

        #decrypt the kek using the decrypted folder password
        kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),
                         length=32,
                         salt=self.kek_db[folder_path]["salt"],
                         iterations=100000,
                         backend=default_backend())
        folder_key = kdf.derive(folder_pwd)
        f = Fernet(urlsafe_b64encode(folder_key))
        folder_kek = f.decrypt(stored_kek)

        if self.kek_db[folder_path]["rotate"]:
            print(
                "Key rotation happened. Reencrypting all DEKs of files in this directory with the new KEK."
            )

            new_kek = Fernet.generate_key()
            new_f = Fernet(new_kek)
            f = Fernet(folder_kek)

            for currentFile in os.listdir(path_secure + folder_path):
                if currentFile == name:
                    continue
                file_encrypted_dek = self.dek_db[folder_path + "/" +
                                                 currentFile]['dek']
                file_dek = f.decrypt(file_encrypted_dek)
                new_file_encrypted_dek = new_f.encrypt(file_dek)
                self.dek_db[folder_path + "/" + currentFile].update(
                    {"dek": new_file_encrypted_dek})

            f = Fernet(urlsafe_b64encode(folder_key))
            new_encrypted_kek = f.encrypt(new_kek)
            self.kek_db[folder_path].update({
                "decryption_kek": new_encrypted_kek,
                "encryption_kek": new_encrypted_kek
            })
            self.kek_db[folder_path].update({"rotate": False})
            folder_kek = new_kek

        #encrypt dek using the decrypted folder kek
        f = Fernet(folder_kek)
        dek = f.encrypt(dek)

        #store encrypted data encrytion key, authentication tag and initialization vector in dek database
        self.dek_db[file_name].update({'dek': dek, 'tag': tag, 'iv': iv})
Exemplo n.º 14
0
 def scrypt(self, salt):
     backend = default_backend()
     return Scrypt(salt=salt, length=32, n=2**15, r=8, p=1, backend=backend)
Exemplo n.º 15
0
 def scrypt(password, salt, N, r, p, dk_len):
     kdf = Scrypt(salt, dk_len, N, r, p, backend)
     return kdf.derive(password)
Exemplo n.º 16
0
import os
import getpass
import base64

from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
from cryptography.hazmat.backends import default_backend
from cryptography.fernet import Fernet

backend = default_backend()
salt = os.urandom(16)

kdf = Scrypt(salt=salt, length=32, n=2**14, r=8, p=1, backend=backend)
Exemplo n.º 17
0
 def hash_pw(cls, pw, salt, params=_Scrypt_params):
     return b64encode(
         Scrypt(salt=salt, backend=default_backend(),
                **params).derive(pw[:128].encode("utf-8"))).decode("ascii")
Exemplo n.º 18
0
                  for _ in range(3)), 'UTF-8') for _ in range(3)
]

pass_to_key = {}
key_to_pass = {}
passes = []
keys = []
ans = [b'', b'', b'']

for c1 in string.ascii_lowercase:
    for c2 in string.ascii_lowercase:
        for c3 in string.ascii_lowercase:
            val = bytes(''.join([c1, c2, c3]), 'UTF-8')
            kdf = Scrypt(salt=b'',
                         length=16,
                         n=2**4,
                         r=8,
                         p=1,
                         backend=default_backend())
            key = kdf.derive(val)
            pass_to_key[val] = key
            key_to_pass[key] = val
            passes.append(val)
            keys.append(key)

############################# Query Functions ###################################


def menu(whi):
    print("INMENU")
    for _ in range(5):
        print(r.recvline())
Exemplo n.º 19
0
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
import binascii
import json
import getpass

v_newpassword = input('newpassword:  '******'data3.txt') as json_file:
    data = json.load(json_file)
    #print(data['luca']['password'])
    salt_encoded = data['luca']['salt']
salt_decoded = base64.urlsafe_b64decode(salt_encoded)
kdf = Scrypt(
    salt=salt_decoded,
    length=32,
    n=2**14,
    r=8,
    p=1,
)
key = kdf.derive(v_password.encode('utf-8'))
#print("v_password encoded ",v_password.encode('utf-8'))
key_encoded = base64.urlsafe_b64encode(key)
#print(key_encoded)
f = Fernet(key_encoded)
try:
    msg = f.decrypt(bytes(data['luca']['password'], 'ascii'))
except InvalidSignature as e:
    errorObj, = e.args
    print("Error Code:", errorObj.code)
    print("Error Message:", errorObj.message)
    print("EXIT signature in decrypt!!!")
Exemplo n.º 20
0
def encrypt():
    if SHA256.new(sys.argv[2].encode()).hexdigest() != masterPassword:
        print("Wrong master password!")
        exit(1)

    address = SHA256.new(sys.argv[3].encode()).hexdigest().encode()
    password = sys.argv[4].encode()

    salt = os.urandom(16)
    # with open('extras', 'ab') as file:
    #     file.write(deWindowsize(salt))
    #     file.write('\n'.encode())
    # derive
    kdf = Scrypt(
        salt=salt,
        length=16,
        n=2**14,
        r=4,
        p=1,
    )
    key = kdf.derive(sys.argv[2].encode())

    cipher = AES.new(key, AES.MODE_CBC, iv=address[0:16])

    cipher_password = cipher.encrypt(pad(password, AES.block_size))

    lineNumber = None
    try:
        with open('address', 'r') as file:
            if address.decode() in file.read():
                lineNumber = findAddressLineNumber(address)
    except FileNotFoundError:
        pass

    # check if address already exists in database
    if lineNumber is None:
        with open('address', 'a+') as file:
            file.write(address.decode())
            file.write('\n')

        with open('pass', 'ab+') as file:
            file.write(deWindowsize(cipher_password))
            file.write('\n'.encode())

        with open('extras', 'ab+') as file:
            file.write(deWindowsize(salt))
            file.write('\n'.encode())
    else:
        with open('pass', 'rb') as file:
            data = file.readlines()
        with open('pass', 'wb+') as file:
            data[lineNumber] = deWindowsize(cipher_password)
            data[lineNumber] += '\n'.encode()
            file.writelines(data)

        with open('extras', 'rb') as file:
            data2 = file.readlines()
        with open('extras', 'wb+') as file:
            data2[lineNumber] = deWindowsize(salt)
            data2[lineNumber] += '\n'.encode()
            file.writelines(data2)
    print('Password set!')
Exemplo n.º 21
0
 def GenerateKey(self):
     kdf = Scrypt(salt=self.salt, length=32, n=2**14, r=8, p=1)
     key = base64.urlsafe_b64encode(kdf.derive(self.password_key))
     return key
Exemplo n.º 22
0
import os
import base64
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
import binascii
import json
#salt = os.urandom(16)
salt = b'6s\xa5\x90\xac|M-K?\x9c\xba\x92}1\xee'
#with same salt we got same key
print(salt.hex())
print(bytes.fromhex('3673a590ac7c4d2d4b3f9cba927d31ee'))
# derive
kdf = Scrypt(
    salt=salt,
    length=32,
    n=2**14,
    r=8,
    p=1,
)
key = kdf.derive(b"my great password")
print(key)
print("Key: ", binascii.hexlify(bytearray(key)))
# verify
kdf = Scrypt(
    salt=salt,
    length=32,
    n=2**14,
    r=8,
    p=1,
)
kdf.verify(b"my great password", key)
Exemplo n.º 23
0
    def getDek(self, file_name):
        #get folder path by eliminating the file name of file path
        folder_path = "/".join(file_name.split("/")[0:-1])

        #get user password
        #compare entered password to stored hash of correct user password
        #repeated until they are equal
        while True:
            pwd = input("Enter your user password")
            kdf = Scrypt(salt=self.users[self.currentUser]["salt"],
                         length=32,
                         n=2**4,
                         r=8,
                         p=1,
                         backend=default_backend())
            try:
                kdf.verify(pwd.encode(), self.users[self.currentUser]["pwd"])
            except InvalidKey:
                print("The password is wrong.")
                continue
            else:
                break

        #get encrypted folder password and folder kek
        encrypted_folder_pwd = self.users[
            self.currentUser]["folders"][folder_path]
        encrypted_kek = self.getDecryptionFolderKek(folder_path)

        #decrypt folder password
        kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),
                         length=32,
                         salt=self.users[self.currentUser]["salt"],
                         iterations=100000,
                         backend=default_backend())
        pwd_key = kdf.derive(pwd.encode())
        f = Fernet(urlsafe_b64encode(pwd_key))
        folder_pwd = f.decrypt(encrypted_folder_pwd)

        #decrypt kek
        kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),
                         length=32,
                         salt=self.kek_db[folder_path]["salt"],
                         iterations=100000,
                         backend=default_backend())
        folder_key = kdf.derive(folder_pwd)
        f = Fernet(urlsafe_b64encode(folder_key))
        kek = f.decrypt(encrypted_kek)

        #decrypt dek
        f = Fernet(kek)
        dek = f.decrypt(self.dek_db[file_name]['dek'])

        if self.kek_db[folder_path]["rotate"]:
            print(
                "Key rotation happened. Reencrypting all DEKs of files in this directory with the new KEK."
            )

            new_kek = Fernet.generate_key()
            new_f = Fernet(new_kek)

            for currentFile in os.listdir(path_secure + folder_path):
                file_encrypted_dek = self.dek_db[folder_path + "/" +
                                                 currentFile]['dek']
                file_dek = f.decrypt(file_encrypted_dek)
                new_file_encrypted_dek = new_f.encrypt(file_dek)
                self.dek_db[folder_path + "/" + currentFile].update(
                    {"dek": new_file_encrypted_dek})

            f = Fernet(urlsafe_b64encode(folder_key))
            new_encrypted_kek = f.encrypt(new_kek)
            self.kek_db[folder_path].update({
                "decryption_kek": new_encrypted_kek,
                "encryption_kek": new_encrypted_kek
            })
            self.kek_db[folder_path].update({"rotate": False})

        return dek
Exemplo n.º 24
0
        print("Decrypting...")
        # Prevent bruteforce attacks...
        time.sleep(query_delay)
        try:
            nonce, ciphertext = ct.split(",")
            nonce = b64decode(nonce)
            ciphertext = b64decode(ciphertext)
        except:
            print(
                "ERROR: Ciphertext has invalid format. Must be of the form \"nonce,ciphertext\", where nonce and ciphertext are base64 strings."
            )
            continue

        kdf = Scrypt(salt=b'',
                     length=16,
                     n=2**4,
                     r=8,
                     p=1,
                     backend=default_backend())
        key = kdf.derive(passwords[key_used])
        try:
            cipher = AESGCM(key)
            plaintext = cipher.decrypt(nonce, ciphertext, associated_data=None)
        except:
            print("ERROR: Decryption failed. Key was not correct.")
            continue

        print("Decryption successful")
    elif option == 4:
        print("Bye!")
        break
    else:
Exemplo n.º 25
0
 def generate_hash(password, salt):
     backend = default_backend()
     kdf = Scrypt(salt=salt, length=32, n=2**14, r=8, p=1, backend=backend)
     return kdf.derive(password)
Exemplo n.º 26
0
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
from cryptography.hazmat.backends import default_backend
import os
salt = os.urandom(16)
kdf = Scrypt(salt=salt,
             length=32,
             n=2**14,
             r=8,
             p=1,
             backend=default_backend())
key = kdf.derive(b'motherfucking password')
print(key, '\n', salt)
Exemplo n.º 27
0
def get_scrypt_derivator(salt):
    return Scrypt(salt=salt, length=32, n=16384, r=8, p=1, backend=backend)
Exemplo n.º 28
0
def create_kdf(salt):
    backend = default_backend()
    kdf = Scrypt(salt=salt, length=32, n=2**14, r=8, p=1, backend=backend)
    return kdf
Exemplo n.º 29
0
import os
import sqlite3

from cryptography.hazmat.backends.openssl.backend import backend
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt

USERS = [
    ("ellen", b"09ijnb4rtgb745yrhbfmcfdeiw0a@(#&", 1),
    ("becca", b"908ygiw42*ho3iu98fx", 0),
]

conn = sqlite3.connect("user.db")
c = conn.cursor()

# Make the table
c.execute("CREATE TABLE users (user text, salt blob, pass blob, admin int)")

# Create users
for username, password, admin in USERS:
    salt = os.urandom(16)
    kdf = Scrypt(salt, 32, 2**14, 8, 1, backend)
    hashed = kdf.derive(password)
    c.execute("INSERT INTO users VALUES (?, ?, ?, ?)",
              [username, salt, hashed, admin])

conn.commit()
Exemplo n.º 30
0
            dkLen=100,
            result=
            '08d4bd8bc6a0db2d3afb86e14bb3e219c7e067add953576ebc4678f86c85f5bc819de1fe22877c7d98c2ee11fef9f3a1ca0047a079b3ee35152c31d51b8db57f267050255065b933d65edfc65203e9b964c5c54507eba8b990c8c9106274fa105237550a'
        ),
        dict(
            password=b"You're a master of Karate",
            salt=b'And friendship for Everyone',
            N=1024,
            r=1,
            p=1,
            dkLen=256,
            result=
            '3a3cbca04456f6ee5295460171a2a2b27e1c28163999f19ab1e2eeda01e355d904627c6baa185087f99f3fee33e4a9ccad1f4230681d77301d2b4f6543023e090faf6e86431a1071f64b693402ceb485469ef33308af104fb1f87b39ecaf733ebc3d73b184c0914fbc4e8eff90777c60172596de79070418f3c9998b6b60640f1d8f3019904b3e20f2920d26c21daf81d0652ffcaffccf734773e0730900204b56b5bebbfb8c3a31d543f6e3ac5f4e1431a864da87c239eefec8e462d458ee2d214646864e9207e15f66a3782b52bb5158152d757d0ca25d2062235ee76c431e5016b3a52cd5b575e3a26aba95654d5b9a991527f5a19d7275ac4f9889081ee9'
        ),
    ]

    for test in Tests:
        multi_backend = MultiBackend([NewScryptBackend(), default_backend()])
        kdf = Scrypt(salt=test['salt'],
                     length=test['dkLen'],
                     n=test['N'],
                     r=test['r'],
                     p=test['p'],
                     backend=multi_backend)
        correct = test['result']
        derived = kdf.derive(test['password'])
        print correct
        print binascii.hexlify(derived)
        print "\n\n"
        assert correct == binascii.hexlify(derived)
Exemplo n.º 31
0
try:
    pvt_key = unhexlify(a2b_base64(pvt_key))  #  funny!
except Error:
    print('invalid .pem file')
    sys.exit(1)

if not len(pvt_key) == 64:
    print('invalid .pem file')
    sys.exit(1)

backend = default_backend()

# derive the encryption key

salt = os.urandom(32)
kdf = Scrypt(salt=salt, length=32, n=4096, r=8, p=1, backend=backend)
key = kdf.derive(bytes(password.encode()))

# encrypt the private key with half of the encryption key

iv = os.urandom(16)
encryption_key = key[0:16]
cipher = Cipher(algorithms.AES(encryption_key), modes.CTR(iv), backend=backend)
encryptor = cipher.encryptor()
ciphertext = encryptor.update(pvt_key) + encryptor.finalize()

# compute the MAC, keyed with the other half of the encryption key
# (this is the only algorithm not explicitly declared but it outputs
# 256 bits and the most obviuos guess of SHA256 is also the right one)

hmac_key = key[16:32]
Exemplo n.º 32
0
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
from cryptography.hazmat.backends import default_backend
import os
key = b'\x95\xda\nr\x0b\xed\xe8:4Q\xb7\x9f\xf8\xe0\x953\xadBvUN\x17KC\xbd\xdb\x93?:\x91O\x9f'
salt = b'\x1dkC;\xda\x11^\xa4zMb\xcfr`\r\x1b'
kdf = Scrypt(salt=salt,
             length=32,
             r=8,
             p=1,
             n=2**14,
             backend=default_backend())
kdf.verify(b'motherfucking password', key)
print("Success! (Exception if mismatch)")
Exemplo n.º 33
0
 def test_invalid_p(self, backend):
     with pytest.raises(ValueError):
         Scrypt(b"NaCl", 64, 2, 8, 0, backend)
Exemplo n.º 34
0
def derive_key(password, salt):
    return Scrypt(salt=salt, length=32, n=2**20, r=8,
                  p=1).derive(password.encode())
Exemplo n.º 35
0
import os
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
from cryptography.hazmat.backends import default_backend

salt = os.urandom(16)

kdf = Scrypt(salt=salt, length=32,
                n=2**14, r=8, p=1,
                backend=default_backend())

key = kdf.derive(b"my great password")
print("KDF output:", key.hex())

kdf = Scrypt(salt=salt, length=32,
             n=2**14, r=8, p=1,
             backend=default_backend())
kdf.verify(b"my great password", key)
print("Success! (Exception if mismatch)")

# If we got here, we passed
print("[PASS]")
Exemplo n.º 36
0
 def __init_cipher(self):
     scrypt = Scrypt(self.salt, length=32, n=2**14, r=8, p=1)
     key = scrypt.derive(bytes(self.password, encoding='utf8'))
     cipher = AESGCM(key)
     return cipher