Python pbkdf2.PBKDF2 Examples

The following are 28 code examples of pbkdf2.PBKDF2(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pbkdf2 , or try the search function .
Example #1
Source File: keys.py    From nowallet with MIT License 6 votes vote down vote up
def derive_key(salt: str, passphrase: str, hd: bool = True) -> \
        Union[int, Tuple[int, bytes]]:
    key_length = 64 if hd else 32  # type: int

    t1 = and_split(bytes(salt, "utf-8"))  # type: Tuple[bytes, bytes]
    salt1, salt2 = t1
    t2 = and_split(bytes(passphrase, "utf-8"))  # type: Tuple[bytes, bytes]
    pass1, pass2 = t2

    scrypt_key = scrypt.hash(
        pass1, salt1,
        N=1 << 18, buflen=key_length)  # type: bytes
    pbkdf2_key = pbkdf2.PBKDF2(
        pass2, salt2,
        iterations=1 << 16,
        digestmodule=SHA256).read(key_length)  # type: bytes
    merged = xor_merge(scrypt_key, pbkdf2_key)  # type: bytes

    if hd:
        secret_exp = int(merged[0:32].hex(), 16)  # type: int
        chain_code = merged[32:]  # type: bytes
        return secret_exp, chain_code

    return int(merged.hex(), 16) 
Example #2
Source File: pmkid.py    From WiFiBroot with GNU General Public License v3.0 6 votes vote down vote up
def crack_the_pmk(self, _hash):
		if type(self.passwords) == str:
			_pass_list = self.passwords.split(',')
		else:
			_file = open(self.dict, 'r')
			_pass_list = self.d_passes+_file.read().splitlines()
			_file.close()

		_last_pass = ''

		for _pass in _pass_list:
			self.pull.up("Currently Checking: %s%s%s" % (self.pull.BOLD, self.printing_pass(_last_pass, _pass.rstrip('\n')), self.pull.END))
			_last_pass = _pass.rstrip('\n')
			_pmk = PBKDF2(_pass, self.essid, 4096).read(32)
			_ap = binascii.a2b_hex(self.ap.replace(':', '').lower())
			_cl = binascii.a2b_hex(self.cl.replace(':', '').lower())
			_pmk_fs = "PMK Name"
			_hash_ = hmac.new(_pmk, _pmk_fs+_ap+_cl, hashlib.sha1).hexdigest()[:32]
			if _hash == _hash_:
				return (_pass, self.hexdump(_pmk), self.hexdump(_hash_))
			else:
				if _pass != _pass_list[-1]:
					self.pull.lineup()

		return (None, '', '') 
Example #3
Source File: captures.py    From WiFiBroot with GNU General Public License v3.0 6 votes vote down vote up
def crack(self, _pm_, _ap_, _cl_, _ess_):
		_last_pass = ''
		for _pass in self.passes:
			self.pull.up("Currently Checking: %s%s%s" % (self.pull.BLUE, self.printing_pass(_last_pass, _pass), self.pull.END))
			_last_pass = _pass
			_pmk = PBKDF2(_pass, binascii.unhexlify(_ess_), 4096).read(32)
			_ap = binascii.a2b_hex(_ap_)
			_cl = binascii.a2b_hex(_cl_)
			_pmk_string = "PMK Name"
			_hash = hmac.new(_pmk, _pmk_string+_ap+_cl, hashlib.sha1).hexdigest()[:32]
			if _hash == _pm_:
				return (_pass, _pmk)
			else:
				if _pass != self.passes[-1]:
					self.pull.lineup()
		return (None, None) 
Example #4
Source File: captures.py    From WiFiBroot with GNU General Public License v3.0 6 votes vote down vote up
def loop(self):
		last_pass__ = ''
		for _pass in self.passes:
			self.pull.up('Current Password: %s' % self.printing_pass(last_pass__, _pass)); last_pass__ = _pass
			_pmk = PBKDF2(_pass, self.essid, 4096).read(32)
			_ptk = self.customPRF512(_pmk, "Pairwise key expansion", self.key_data)
			_mic = hmac.new(_ptk[0:16], self.payload, hashlib.md5).hexdigest()
			_mic_ = hmac.new(_ptk[0:16], self.payload, hashlib.sha1).hexdigest()[:32]
			if self.mic == _mic or self.mic == _mic_:
				self.pull.use("CRACKED! Key Found %s[%s]%s" % (self.pull.GREEN, _pass, self.pull.END))
				self.pull.right("PMK =>"); print self.hexdump(_pmk)
				self.pull.right("PTK =>"); print self.hexdump(_ptk)
				self.pull.right("MIC =>"); print self.hexdump(_mic if self.mic == _mic else _mic_)
				return
			else:
				if _pass != self.passes[-1]:
					self.pull.lineup() 
Example #5
Source File: cracker.py    From WiFiBroot with GNU General Public License v3.0 5 votes vote down vote up
def hash(self, pass__):
		pmk__ = PBKDF2(pass__, self.essid, 4096).read(32)
		ptk__ = self.customPRF512(pmk__, self.__PKE_, self.key_data)
		#if self.encryption == 'WPA':
		mic__ = hmac.new(ptk__[0:16], self.payload, hashlib.md5).digest()
		#elif self.encryption == 'WPA2':
		mic___ = hmac.new(ptk__[0:16], self.payload, hashlib.sha1).digest()
		if self.mic == binascii.hexlify(mic__):
			self.__CRACKED = (True, pass__)
			return (pmk__, ptk__, mic__)
		elif self.mic == binascii.hexlify(mic___)[:32]:
			self.__CRACKED = (True, pass__)
			return (pmk__, ptk__, mic___)
		else:
			return (pmk__, ptk__, mic__) 
Example #6
Source File: rsCrypto.py    From redsails with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, key):
		# Ill implement this later -_-
		#self.keyDerivation = PBKDF2(key, os.urandom(8)).read(32)
		
		self.keyDerivation = PBKDF2(key, "DEADLIST").read(32)
		self.iv = iv(AES.block_size) 
Example #7
Source File: rsCrypto.py    From redsails with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, key):
		# Ill implement this later -_-
		#self.keyDerivation = PBKDF2(key, os.urandom(8)).read(32)
		
		self.keyDerivation = PBKDF2(key, "DEADLIST").read(32)
		self.iv = iv(AES.block_size)

		self.tryToKillPasswordInMemory(key) 
Example #8
Source File: keystore.py    From web3-gear with MIT License 5 votes vote down vote up
def pbkdf2_hash(val, params):
    assert params["prf"] == "hmac-sha256"
    return pbkdf2.PBKDF2(val, decode_hex(params["salt"]), params["c"],
                         SHA256).read(params["dklen"]) 
Example #9
Source File: aescipher.py    From Audible with GNU Affero General Public License v3.0 5 votes vote down vote up
def derive_from_pbkdf2(password: str, *, key_size: int, salt: bytes,
                       kdf_iterations: int, hashmod, mac):

    kdf = PBKDF2(password, salt, min(kdf_iterations, 65535), hashmod, mac)
    return kdf.read(key_size) 
Example #10
Source File: crypto.py    From certitude with GNU General Public License v2.0 5 votes vote down vote up
def keyFromText(text, salt):
    optimalSize = max(AES.key_size)
    return PBKDF2(text, salt).read(optimalSize)


# Pad a message to a multiple of size
# Repeats chr(X) X times at the end of the message (X>0) 
Example #11
Source File: mnemonic.py    From EasyStorj with MIT License 5 votes vote down vote up
def to_seed(cls, mnemonic, passphrase=''):
        mnemonic = cls.normalize_string(mnemonic)
        passphrase = cls.normalize_string(passphrase)
        return PBKDF2(mnemonic, u'mnemonic' + passphrase, iterations=PBKDF2_ROUNDS, macmodule=hmac, digestmodule=hashlib.sha512).read(64) 
Example #12
Source File: nanocore.py    From bamfdetect with MIT License 5 votes vote down vote up
def derive_key(guid, coded_key):
    generator = PBKDF2(guid, guid, 8)
    aes_iv = generator.read(16)
    aes_key = generator.read(16)
    derived_key = decrypt_aes(aes_key, aes_iv, coded_key)
    return derived_key 
Example #13
Source File: secureStorage.py    From builder with GNU Affero General Public License v3.0 5 votes vote down vote up
def getEncryptionKey(password, salt):
  assert password
  assert salt

  saltbytes = urlsafe_b64decode(salt.encode('utf-8'))
  hashThing = PBKDF2(password, saltbytes)
  return hashThing.read(32) 
Example #14
Source File: secureStorage.py    From builder with GNU Affero General Public License v3.0 5 votes vote down vote up
def getEncryptionKey(password, salt):
  assert password
  assert salt

  saltbytes = urlsafe_b64decode(salt.encode('utf-8'))
  hashThing = PBKDF2(password, saltbytes)
  return hashThing.read(32) 
Example #15
Source File: crypto.py    From RATDecoders with MIT License 5 votes vote down vote up
def derive_pbkdf2(key, salt, iv_length, key_length, iterations=8):
    generator = PBKDF2(key, salt, iterations)
    derived_iv = generator.read(iv_length)
    derived_key = generator.read(key_length)
    return derived_iv, derived_key 
Example #16
Source File: mnemonic.py    From Uwallet with MIT License 5 votes vote down vote up
def mnemonic_to_seed(cls, mnemonic, passphrase):
        PBKDF2_ROUNDS = 2048
        mnemonic = prepare_seed(mnemonic)
        return pbkdf2.PBKDF2(mnemonic, 'uwallet' + passphrase, iterations=PBKDF2_ROUNDS,
                             macmodule=hmac, digestmodule=hashlib.sha512).read(64) 
Example #17
Source File: wallet.py    From Uwallet with MIT License 5 votes vote down vote up
def mnemonic_to_seed(mnemonic, passphrase):
        # See BIP39
        PBKDF2_ROUNDS = 2048
        mnemonic = normalize('NFKD', ' '.join(mnemonic.split()))
        passphrase = BIP44_Wallet.normalize_passphrase(passphrase)
        return pbkdf2.PBKDF2(mnemonic, 'mnemonic' + passphrase,
                             iterations=PBKDF2_ROUNDS, macmodule=hmac,
                             digestmodule=hashlib.sha512).read(64) 
Example #18
Source File: mnemonic.py    From lbry-sdk with MIT License 5 votes vote down vote up
def mnemonic_to_seed(mnemonic, passphrase=''):
        pbkdf2_rounds = 2048
        mnemonic = normalize_text(mnemonic)
        passphrase = normalize_text(passphrase)
        return pbkdf2.PBKDF2(
            mnemonic, passphrase, iterations=pbkdf2_rounds, macmodule=hmac, digestmodule=hashlib.sha512
        ).read(64) 
Example #19
Source File: predatorpain.py    From CIRTKit with MIT License 5 votes vote down vote up
def decrypt_string(key, salt, coded):
    #try:
        # Derive key
        generator = PBKDF2(key, salt)
        aes_iv = generator.read(16)
        aes_key = generator.read(32)
        # Crypto
        mode = AES.MODE_CBC
        cipher = AES.new(aes_key, mode, IV=aes_iv)
        value = cipher.decrypt(b64decode(coded)).replace('\x00', '')
        return value#.encode('hex')
    #except:
        #return False

# Get a list of strings from a section 
Example #20
Source File: nanocore.py    From CIRTKit with MIT License 5 votes vote down vote up
def derive_key(guid, coded_key):
    try:
        from pbkdf2 import PBKDF2
    except:
        print "[!] Unable to derive a key. requires 'sudo pip install pbkdf2'"
        sys.exit()
    generator = PBKDF2(guid, guid, 8)
    aes_iv = generator.read(16)
    aes_key = generator.read(16)
    derived_key = decrypt_aes(aes_key, aes_iv, coded_key)
    return derived_key 
Example #21
Source File: hawkeye.py    From CIRTKit with MIT License 5 votes vote down vote up
def decrypt_string(key, salt, coded):
    #try:
        # Derive key
        generator = PBKDF2(key, salt)
        aes_iv = generator.read(16)
        aes_key = generator.read(32)
        # Crypto
        mode = AES.MODE_CBC
        cipher = AES.new(aes_key, mode, IV=aes_iv)
        value = cipher.decrypt(b64decode(coded)).replace('\x00', '')
        return value#.encode('hex')
    #except:
        #return False

# Get a list of strings from a section 
Example #22
Source File: handshake.py    From pyDot11 with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, psk = None, essid = None, pcap = False):
        self.pt = PE.pt
        if psk is not None and essid is not None:
            if os.path.isfile('handshakes.sqlite'):
                os.remove('handshakes.sqlite')
            self.con = lite.connect('handshakes.sqlite')
            self.con.text_factory = str
            self.db = self.con.cursor()
            self.tgtInfo = {}
            self.availTgts = set()
            self.catchDict = {}
            self.encDict = {}
            self.alert = set()
            self.pke = 'Pairwise key expansion'
            self.pmk = PBKDF2(psk, essid, 4096).read(32)
            self.db.execute('CREATE TABLE IF NOT EXISTS\
                                "shakes"("pkt" TEXT,\
                                         "vmac" TEXT,\
                                         "bmac" TEXT,\
                                         "nonce" TEXT,\
                                         "e_num" TEXT,\
                                         UNIQUE(vmac, bmac, e_num));')
            self.con.commit()
            if pcap is True:
                self.eapolTrack = PcapWriter('eapols.pcap', sync = True)
                self.pcap = pcap
            else:
                self.eapolTrack = None
                self.pcap = None 
Example #23
Source File: trezor.py    From encompass with GNU General Public License v3.0 5 votes vote down vote up
def mnemonic_to_seed(self, mnemonic, passphrase):
        # trezor uses bip39
        import pbkdf2, hashlib, hmac
        PBKDF2_ROUNDS = 2048
        mnemonic = unicodedata.normalize('NFKD', ' '.join(mnemonic.split()))
        passphrase = unicodedata.normalize('NFKD', passphrase)
        return pbkdf2.PBKDF2(mnemonic, 'mnemonic' + passphrase, iterations = PBKDF2_ROUNDS, macmodule = hmac, digestmodule = hashlib.sha512).read(64) 
Example #24
Source File: mnemonic.py    From encompass with GNU General Public License v3.0 5 votes vote down vote up
def mnemonic_to_seed(self, mnemonic, passphrase):
        PBKDF2_ROUNDS = 2048
        mnemonic = prepare_seed(mnemonic)
        return pbkdf2.PBKDF2(mnemonic, 'mnemonic' + passphrase, iterations = PBKDF2_ROUNDS, macmodule = hmac, digestmodule = hashlib.sha512).read(64) 
Example #25
Source File: mnemonic.py    From torba with MIT License 5 votes vote down vote up
def mnemonic_to_seed(mnemonic, passphrase=u''):
        pbkdf2_rounds = 2048
        mnemonic = normalize_text(mnemonic)
        passphrase = normalize_text(passphrase)
        return pbkdf2.PBKDF2(
            mnemonic, passphrase, iterations=pbkdf2_rounds, macmodule=hmac, digestmodule=hashlib.sha512
        ).read(64) 
Example #26
Source File: accounts.py    From pyquarkchain with MIT License 5 votes vote down vote up
def _decode_keystore_json(jsondata, password):
        # Get key derivation function (kdf) and parameters
        kdfparams = jsondata["crypto"]["kdfparams"]

        # Compute derived key
        derivedkey = pbkdf2.PBKDF2(
            password, decode_hex(kdfparams["salt"]), kdfparams["c"], SHA256
        ).read(kdfparams["dklen"])

        assert len(derivedkey) >= 32, "Derived key must be at least 32 bytes long"

        # Get cipher and parameters and decrypt using AES
        cipherparams = jsondata["crypto"]["cipherparams"]
        enckey = derivedkey[:16]
        iv = int.from_bytes(decode_hex(cipherparams["iv"]), byteorder="big")
        ctr = Counter.new(128, initial_value=iv, allow_wraparound=True)
        encryptor = AES.new(enckey, AES.MODE_CTR, counter=ctr)
        ctext = decode_hex(jsondata["crypto"]["ciphertext"])
        o = encryptor.decrypt(ctext)

        # Compare the provided MAC with a locally computed MAC
        mac1 = sha3(derivedkey[16:32] + ctext)
        mac2 = decode_hex(jsondata["crypto"]["mac"])
        if mac1 != mac2:
            raise ValueError("MAC mismatch. Password incorrect?")
        return o 
Example #27
Source File: hd.py    From pybtcfork with MIT License 4 votes vote down vote up
def from_mnemonic(cls, mnemonic, password=b'', path=b'm', testnet=False):
        binary_seed = bytearray()
        offset = 0
        words = mnemonic.split()
        if len(words) not in (12, 15, 18, 21, 24):
            raise RuntimeError('you need 12, 15, 18, 21, or 24 words')
        for word in words:
            index = WORD_LOOKUP[word]
            remaining = 11
            while remaining > 0:
                bits_needed = 8 - offset
                if remaining == bits_needed:
                    if bits_needed == 8:
                        binary_seed.append(index)
                    else:
                        binary_seed[-1] |= index
                    offset = 0
                    remaining = 0
                elif remaining > bits_needed:
                    if bits_needed == 8:
                        binary_seed.append(index >> (remaining - 8))
                    else:
                        binary_seed[-1] |= index >> (remaining - bits_needed)
                    remaining -= bits_needed
                    offset = 0
                    # lop off the top 8 bits
                    index &= (1 << remaining) - 1
                else:
                    binary_seed.append(index << (8 - remaining))
                    offset = remaining
                    remaining = 0
        checksum_length_bits = len(words)*11 // 33
        num_remainder = checksum_length_bits % 8
        if num_remainder:
            checksum_length = checksum_length_bits // 8 + 1
            bits_to_ignore = 8 - num_remainder
        else:
            checksum_length = checksum_length_bits // 8
            bits_to_ignore = 0
        raw = bytes(binary_seed)
        data, checksum = raw[:-checksum_length], raw[-checksum_length:]
        computed_checksum = bytearray(sha256(data).digest()[:checksum_length])
        # ignore the last bits_to_ignore bits
        computed_checksum[-1] &= 256 - (1 << (bits_to_ignore + 1) - 1)
        if checksum != bytes(computed_checksum):
            raise RuntimeError('words fail checksum: {}'.format(
                hexlify(raw).decode('ascii')))
        normalized_words = []
        for word in words:
            normalized_words.append(WORD_LIST[WORD_LOOKUP[word]])
        normalized_mnemonic = ' '.join(normalized_words)
        seed = PBKDF2(
            normalized_mnemonic,
            b'mnemonic' + password,
            iterations=PBKDF2_ROUNDS,
            macmodule=hmac,
            digestmodule=sha512,
        ).read(64)
        return cls.from_seed(seed, path, testnet=testnet) 
Example #28
Source File: accounts.py    From pyquarkchain with MIT License 4 votes vote down vote up
def _make_keystore_json(self, password):
        """
        Generate the keystore json that follows the Version 3 specification:
        https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition#definition

        Uses pbkdf2 for password encryption, and AES-128-CTR as the cipher.
        """
        # Get the hash function and default parameters
        kdfparams = {
            "prf": "hmac-sha256",
            "dklen": 32,
            "c": 262144,
            "salt": encode_hex(os.urandom(16)),
        }

        # Compute derived key
        derivedkey = pbkdf2.PBKDF2(
            password, decode_hex(kdfparams["salt"]), kdfparams["c"], SHA256
        ).read(kdfparams["dklen"])

        # Produce the encryption key and encrypt using AES
        enckey = derivedkey[:16]
        cipherparams = {"iv": encode_hex(os.urandom(16))}
        iv = int.from_bytes(decode_hex(cipherparams["iv"]), byteorder="big")
        ctr = Counter.new(128, initial_value=iv, allow_wraparound=True)
        encryptor = AES.new(enckey, AES.MODE_CTR, counter=ctr)
        c = encryptor.encrypt(self.identity.key)

        # Compute the MAC
        mac = sha3(derivedkey[16:32] + c)

        # Return the keystore json
        return {
            "crypto": {
                "cipher": "aes-128-ctr",
                "ciphertext": encode_hex(c),
                "cipherparams": cipherparams,
                "kdf": "pbkdf2",
                "kdfparams": kdfparams,
                "mac": encode_hex(mac),
                "version": 1,
            },
            "id": self.uuid,
            "version": 3,
        }