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)
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)
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)
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)
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 _derive_password(self, password): """ Derives a password with a salt :param password: clear text password :type password: str :return: derived password and salt used encoded in base64 :rtype: (str, str) """ salt = urandom(SALT_SIZE) password = bytes(password, "utf-8") kdf = Scrypt( salt = salt, length = 32, n = 2**14, r = 8, p = 1, backend = default_backend() ) derived_password = kdf.derive(password) return b64encode(derived_password), b64encode(salt)
def test_hand_shake_verify_password_return_true_if_given_password_is_correct_and_role_is_server( ): # Given password_to_verify = b"test_password" password_to_derive = b"test_password" password_salt = os.urandom(16) expected_result = True # derive kdf = Scrypt( salt=password_salt, length=32, n=2**14, r=8, p=1, ) derived_password = kdf.derive(password_to_derive) authentication_information_server = { "password": { Handshake.PASSWORD_AUTH_METHOD_DERIVED_PASSWORD_KEY: derived_password, Handshake.PASSWORD_AUTH_METHOD_SALT_KEY: password_salt } } allowed_authentication_methods = ["password"] server = Handshake( role=Handshake.SERVER, authentication_information=authentication_information_server, allowed_authentication_methods=allowed_authentication_methods) # When result = server._verify_password(password_to_verify=password_to_verify) # Then assert result == expected_result
def keyeststep10(): received = ast.literal_eval(pkt1.smsg.actMsg) salt = received["salt"] aesgcm = AESGCM(temp_known_users[addr]["Sab"]) try: u2_pubkey = int( aesgcm.decrypt(received["nonceforu2pubkey"], received["enc_u2pubkey"], None)) ssAB = pow(u2_pubkey, keyeststep8.u1_prikey, keyeststep8.s_p) backend = default_backend() # derive kdf = Scrypt(salt=salt, length=32, n=2**14, r=8, p=1, backend=backend) kAB = kdf.derive(bytes(ssAB)) known_users[temp_known_users[addr]["name"]] = { "ssAB": kAB, "addr": addr } aesgcm = AESGCM(kAB) nonceformsg = os.urandom(12) message = aesgcm.encrypt(nonceformsg, keyestfunction.smsg, None) msgtosend = {"nonceformsg": nonceformsg, "msg": message} fillauthpacket(pkt1, "Data", 0, bytes(msgtosend)) sendpacket(pkt1.SerializeToString(), addr[0], addr[1]) except cryptography.exceptions.InvalidTag: print "Decrypt not okay"
def __fernetKey(self, salt, password): backend = default_backend() kdf = Scrypt(salt=salt, length=32, n=2**14, r=8, p=1, backend=backend) key = base64.urlsafe_b64encode(kdf.derive(b"%a" % password)) return Fernet(key)
def kdf(cls, kdf, key, salt=None, dklen=None, verbose=False): assert (isinstance(key, bytes)) if salt is None: salt = os.urandom(32) if dklen is None: dklen = kdf["dklen"] meta = { "name": kdf["name"], "salt": salt.hex(), "dklen": dklen, } t0 = time.time() if kdf["name"] == "scrypt": N = kdf.get("N", 1024 * 1024) r = kdf.get("r", 8) p = kdf.get("p", 1) meta.update({ "N": N, "r": r, "p": p, }) scrypt = Scrypt(salt=salt, length=dklen, n=N, r=r, p=p, backend=_backend) dkey = scrypt.derive(key) else: raise NotImplementedError(kdf["name"]) t1 = time.time() if verbose: print("Key derivation took %.3f sec" % (t1 - t0)) return (meta, dkey)
def test_verify_password_scrypt_return_true_if_given_password_is_correct_and_derived_with_scrypt( ): # Given password_to_verify = b"test_password" password_to_derive = b"test_password" password_salt = os.urandom(16) expected_result = True # derive kdf = Scrypt( salt=password_salt, length=32, n=2**14, r=8, p=1, ) derived_password = kdf.derive(password_to_derive) # When result = verify_password_scrypt(password_to_verify=password_to_verify, derived_password=derived_password, password_salt=password_salt) # Then assert result == expected_result
def hash_function(p, hashfunc="bcrypt", salt=None): """Generate hash from input string. Arguments: p {str, bytes} -- The input to be hashed. Keyword Arguments: hashfunc {str} -- Hashing algorithm to use. Options are "sha1" and "scrypt". (default: {"sha1"}) Returns: bytes -- Hash of the input """ if isinstance(p, str): # Convert str to bytes if necessary p = p.encode() hashfunc = hashfunc.lower() # Ensure the input will match the conditional case. if hashfunc == "sha1": return hashlib.sha1(p).hexdigest().encode() elif hashfunc == "scrypt": if not salt: salt = b"salt" instance = Scrypt( salt=b"salt", length=32, n=2 ** 14, r=8, p=1, backend=default_backend() ) return instance.derive(p) elif hashfunc == "bcrypt": if not salt: salt = bcrypt.gensalt() return bcrypt.hashpw(p, salt) else: raise ValueError
def decrypt_file(cipherpath, plainpath, password): with open(cipherpath, "rb") as fcipher: # read the IV (12 bytes) and the salt (16 bytes) associated_data = fcipher.read(12+16) iv = associated_data[0:12] salt = associated_data[12:28] # derive the same key from the password + salt kdf = Scrypt(salt=salt, length=32, n=2**14, r=8, p=1, backend=default_backend()) key = kdf.derive(password) # get the tag. GCM tags are always 16 bytes tag = fcipher.read(16) # Construct an AES-GCM Cipher object with the given key and IV # For decryption, the tag is passed in as a parameter decryptor = Cipher( algorithms.AES(key), modes.GCM(iv, tag), backend=default_backend()).decryptor() decryptor.authenticate_additional_data(associated_data) with open(plainpath, "wb+") as fplain: for ciphertext in iter(lambda: fcipher.read(READ_SIZE),b''): plaintext = decryptor.update(ciphertext) fplain.write(plaintext)
def query(ctxt): global r, passwords if REMOTE: menu(3) print("Query") print(r.recvline()) r.sendline(ctxt) print(r.recvline()) s = r.recvline() print("s:", s) if b"ERROR" in s: return 0 print(r.recvline()) r.recvline() return 1 else: nonce, ciphertext = ctxt.split(b",") nonce = b64decode(nonce) ciphertext = b64decode(ciphertext) kdf = Scrypt(salt=b'', length=16, n=2**4, r=8, p=1, backend=default_backend()) key = kdf.derive(passwords[cur_idx]) try: cipher = AESGCM(key) plaintext = cipher.decrypt(nonce, ciphertext, associated_data=None) return 1 except: return 0
def get_key(verbose_pass=False): print("Please write your password") password1 = stdiomask.getpass() password1 = password1.encode() # Okey for this application, if this application is used for storring multiple users data or something like that # A non static salt should be used to avoid rainbow-table vulnerbilities salt = b'u\xcf(\n\xd5\x9c\x05\xffy\x97\x96\xb1@\x1f\rn' time1 = time.time() kdf = Scrypt(salt=salt, length=32, n=2**20, r=8, p=1) #key = base64.urlsafe_b64encode(kdf.derive(password1)) key = kdf.derive(password1) print("It took ", time.time() - time1, " seconds to generate the key") print("Please verify your password") password2 = stdiomask.getpass() password2 = password2.encode() if password2 != password1: print("Passwords didn't match") exit(-1) return key
def decrypt_file(cipherpath, plainpath, password): with open(cipherpath, "rb") as fcipher: associated_data = fcipher.read(12 + 16) iv = associated_data[0:12] salt = associated_data[12:28] # Derive the same password with salt kdf = Scrypt(salt=salt, length=32, n=2**14, r=8, p=1, backend=default_backend()) key = kdf.derive(password) # GCM tags are always 16 bytes tag = fcipher.read(16) decryptor = Cipher(algorithms.AES(key), modes.GCM(iv, tag), backend=default_backend()).decryptor() decryptor.authenticate_additional_data(associated_data) with open(plainpath, "wb+") as fplain: for ciphertext in iter(lambda: fcipher.read(READ_SIZE), b""): plaintext = decryptor.update(ciphertext) fplain.write(plaintext)
def encrypt_file(plainpath, cipherpath, password): salt = os.urandom(16) kdf = Scrypt(salt=salt, length=32, n=2**14, r=8, p=1, backend=default_backend()) key = kdf.derive(password) iv = os.urandom(12) encryptor = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend()).encryptor() associated_data = iv + salt encryptor.authenticate_additional_data(associated_data) with open(cipherpath, "wb+") as fcipher: fcipher.write(b"\x00" * (12 + 16 + 16)) with open(plainpath, "rb") as fplain: for plaintext in iter(lambda: fplain.read(READ_SIZE), b""): ciphertext = encryptor.update(plaintext) fcipher.write(ciphertext) ciphertext = encryptor.finalize() fcipher.write(ciphertext) header = associated_data + encryptor.tag fcipher.seek(0, 0) fcipher.write(header)
def read(args, action): # read the file with contextlib.closing(FileDecryptor(args.archive, None)) as fd: # no decryptor yet # parse the header header = HEADER.parse(fd.read_aad(HEADER.sizeof())) # setup encryption kdf_params = header['kdf_params'] kdf = Scrypt(salt=kdf_params['salt'], length=32, n=kdf_params['n'], r=kdf_params['r'], p=kdf_params['p'], backend=BACKEND) key = kdf.derive(get_password().encode('utf-8')) logging.debug(f'[read()] key={key.hex()}') cipher_params = header['cipher_params'] cipher = Cipher(algorithms.ChaCha20(key, cipher_params['nonce']), modes.Poly1305(), backend=BACKEND) fd.init(cipher.decryptor()) # read the tag fd.read_tag() # read the archive tar = tarfile.open(fileobj=fd, mode='r|*') action(tar)
def aesDecrypt(iv, salt, password, payload): """ Decrypt AndSafe payload Keyword arguments: :param iv: IV for AES in CBC mode. In hexdecimal string format :param salt: salt for scrypt key derivation. In hexdecimal string format :param password: password for decryption. In string format :param payload: payload to decrypt. In hexdecimal string format :return: bytes of decrypted content """ unpadder = padding.PKCS7(128).unpadder() backend = default_backend() kdf = Scrypt(salt=bytes.fromhex(salt), length=32, n=2**14, r=8, p=1, backend=backend) key = kdf.derive(password.encode()) cipher = Cipher(algorithms.AES(key), modes.CBC(bytes.fromhex(iv)), backend=backend) decryptor = cipher.decryptor() return unpadder.update( decryptor.update(bytes.fromhex(payload)) + decryptor.finalize()) + unpadder.finalize()
def aesEncrypt(iv, salt, password, plain): """ Encrypt AndSafe plaintext Keyword arguments: :param iv: IV for AES in CBC mode. In hexdecimal string format :param salt: salt for scrypt key derivation. In hexdecimal string format :param password: password for encryption. In string format :param plain: plaintext to encrypt :return: bytes of encrypted content """ padder = padding.PKCS7(128).padder() backend = default_backend() kdf = Scrypt(salt=bytes.fromhex(salt), length=32, n=2**14, r=8, p=1, backend=backend) key = kdf.derive(password.encode()) cipher = Cipher(algorithms.AES(key), modes.CBC(bytes.fromhex(iv)), backend=backend) encryptor = cipher.encryptor() return encryptor.update( padder.update(str.encode(plain)) + padder.finalize()) + encryptor.finalize()
def scrypt(self): cost = 14 backend = default_backend() salt = os.urandom(16) start_time = time.time() while True: print('--- %s seconds ---' % (time.time() - start_time), "cpu/memory cost factor", cost) if ((time.time() - start_time) < self.running_time): start_time = time.time() kdf = Scrypt(salt=salt, length=32, n=2**cost, r=8, p=1, backend=backend) key = kdf.derive(str.encode(self.password)) else: if ((time.time() - start_time) > self.threshold ): # Check if its way more than acceptable print('--- %s seconds ---' % (time.time() - start_time), "cpu/memory cost factor", cost - 1) else: print('--- %s seconds ---' % (time.time() - start_time), "cpu/memory cost factor", cost) break cost = cost + 1
def authlaststep(d, addr, aupkt1): # print d # print "cc:", d["clientcontri"] # print "secret:", d["secret"] # print "sc:", d["sumcontri"] session_key = pow( pow(long(d["clientcontri"]), long(d["b"]), p) * pow(long(d["secret"]), (d["b"] * d["u"]), p), 1, p) # print "sk:", session_key batch = ast.literal_eval(aupkt1.smsg.actMsg) # print "batch", batch ct = batch["Enc"] # print "ct", ct C3 = batch["C3"] # print 'c3', C3 nonce = batch["nonce"] # print "nonce", nonce salt = batch["salt"] # print "salt", salt c2 = d["C2"] backend = default_backend() # derive kdf = Scrypt(salt=salt, length=32, n=2**14, r=8, p=1, backend=backend) key = kdf.derive(bytes(session_key)) # print "key", key aesgcm = AESGCM(key) try: ct = long(aesgcm.decrypt(nonce, ct, None)) if c2 == ct: # print "values match" nonce2 = os.urandom(12) encc3 = aesgcm.encrypt(nonce2, bytes(C3), None) # print "enc okay" retd = {"encc3": encc3, "nonce2": nonce2} fillauthpacket(aupkt1, "Login", 6, bytes(retd)) # print "pf" sendpacket(aupkt1.SerializeToString(), addr[0], addr[1]) # print "6 sent" connected_users[addr] = { "uname": temp_values[addr]["uname"], "ipaddr": addr[0], "port": addr[1], "skey": key } currusers[temp_values[addr]["uname"]] = { "ipaddr": addr[0], "port": addr[1] } del temp_values[addr] except cryptography.exceptions.InvalidTag: print "Someone entered an incorrect password" fillauthpacket(aupkt1, "Login", 6, "Incorrect") sendpacket(aupkt1.SerializeToString(), addr[0], addr[1])
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'))
def _gen_login_key(password: bytes, identity: bytes): """ Derives a key from a password and identifier. The key is used to decrypt (also unlock) the secret key of a user. """ kdf_input = blake2b(password).digest() ^ blake2b(identity).digest() kdf = Scrypt(b'', 32, 16384, 8, 1, default_backend()) return kdf.derive(kdf_input)
def scrypt(passphrase, salt, scrypt_n=1 << 13, scrypt_r=16, scrypt_p=1): kdf = Scrypt(salt, length=32, n=scrypt_n, r=scrypt_r, p=scrypt_p, backend=default_backend()) return kdf.derive(passphrase)
def generate_key_from_password(password, salt): kdf = Scrypt(salt=salt, length=32, n=2**14, r=8, p=1, backend=default_backend()) key = kdf.derive(password) return key
async def _save_user(email: str, password: str, domain: str) -> None: from kolombo import conf from kolombo.models import User kdf = Scrypt(conf.SALT, length=32, n=2**16, r=8, p=1) b64_password = b64encode(kdf.derive(password.encode("utf-8"))) await User.objects.create(email=email, password=b64_password, domain=domain)
def scrypt(password_bytes, salt, N, r, p, dklen): kdf = Scrypt(salt=salt, length=dklen, n=N, r=r, p=p, backend=default_backend()) hash_bytes = kdf.derive(password_bytes) return binascii.hexlify(hash_bytes).decode()
def scrypt(password, salt, power, hash_len): kdf = Scrypt(salt=salt, length=hash_len, n=2**power, r=8, p=1, backend=default_backend()) key = kdf.derive(password) return key
def load_from_key_file(key_file_json, password): with open(key_file_json) as json_f: keystore = load(json_f) backend = default_backend() # derive the decryption key kdf_name = keystore['crypto']['kdf'] if kdf_name != 'scrypt': raise errors.UnknownDerivationFunction() salt = unhexlify(keystore['crypto']['kdfparams']['salt']) dklen = keystore['crypto']['kdfparams']['dklen'] n = keystore['crypto']['kdfparams']['n'] p = keystore['crypto']['kdfparams']['p'] r = keystore['crypto']['kdfparams']['r'] kdf = Scrypt(salt=salt, length=dklen, n=n, r=r, p=p, backend=backend) key = kdf.derive(bytes(password.encode())) # decrypt the private key with half of the decryption key cipher_name = keystore['crypto']['cipher'] if cipher_name != 'aes-128-ctr': raise errors.UnknownCipher(name=cipher_name) iv = unhexlify(keystore['crypto']['cipherparams']['iv']) ciphertext = unhexlify(keystore['crypto']['ciphertext']) decryption_key = key[0:16] cipher = Cipher(algorithms.AES(decryption_key), modes.CTR(iv), backend=backend) decryptor = cipher.decryptor() plaintext = decryptor.update(ciphertext) + decryptor.finalize() pemified_private_key = b2a_base64(hexlify(plaintext)) hmac_key = key[16:32] h = hmac.HMAC(hmac_key, hashes.SHA256(), backend=backend) h.update(ciphertext) mac = h.finalize() if mac != unhexlify(keystore['crypto']['mac']): raise errors.InvalidKeystoreFilePassword() address_bech32 = keystore['bech32'] private_key = ''.join([ pemified_private_key[i:i + 64].decode() for i in range(0, len(pemified_private_key), 64) ]) key_hex = base64.b64decode(private_key).decode() key_bytes = bytes.fromhex(key_hex) seed = key_bytes[:32] return address_bech32, seed
def scrypt_generate(message): backend = default_backend() salt = os.urandom(16) kdf = Scrypt(salt=salt, length=32, n=2**14, r=8, p=1, backend=backend) key = kdf.derive(message.encode()) print(hexlify(salt).decode(), hexlify(key).decode())
def test_derive(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 binascii.hexlify(scrypt.derive(password)) == derived_key
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'