Python Crypto.Protocol.KDF.PBKDF2 Examples

The following are 30 code examples of Crypto.Protocol.KDF.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 Crypto.Protocol.KDF , or try the search function .
Example #1
Source File: kobackupdec.py    From kobackupdec with MIT License 6 votes vote down vote up
def __decrypt_bkey_v4(self):
        key_salt = self._pwkey_salt[:16]
        logging.debug('KEY_SALT[%s] = %s', len(key_salt),
                      binascii.hexlify(key_salt))

        key = PBKDF2(self._upwd, key_salt, Decryptor.dklen, Decryptor.count,
                     Decryptor.prf)
        logging.debug('KEY[%s] = %s', len(key), binascii.hexlify(key))

        nonce = self._pwkey_salt[16:]
        logging.debug('KEY NONCE[%s] = %s', len(nonce),
                      binascii.hexlify(nonce))

        cipher = AES.new(key, mode=AES.MODE_GCM, nonce=nonce)
        self._bkey = cipher.decrypt(self._e_perbackupkey)[:32]
        logging.debug('BKEY[%s] =   %s',
                      len(self._bkey), binascii.hexlify(self._bkey)) 
Example #2
Source File: kobackupdec.py    From kobackupdec with MIT License 6 votes vote down vote up
def decrypt_package(self, dec_material, data):
        if not self._good:
            logging.warning('well, it is hard to decrypt with a wrong key.')

        if not dec_material.encMsgV3:
            logging.error('cannot decrypt with an empty encMsgV3!')
            return None

        salt = dec_material.encMsgV3[:32]
        counter_iv = dec_material.encMsgV3[32:]

        key = PBKDF2(self._bkey, salt, Decryptor.dklen, Decryptor.count,
                     Decryptor.prf, hmac_hash_module=None)

        counter_obj = Counter.new(128, initial_value=int.from_bytes(
            counter_iv, byteorder='big'), little_endian=False)

        decryptor = AES.new(key, mode=AES.MODE_CTR, counter=counter_obj)
        return decryptor.decrypt(data) 
Example #3
Source File: kobackupdec.py    From kobackupdec with MIT License 6 votes vote down vote up
def decrypt_large_package(self, dec_material, entry):
        if not self._good:
            logging.warning('well, it is hard to decrypt with a wrong key.')

        if not dec_material.encMsgV3:
            logging.error('cannot decrypt with an empty encMsgV3!')
            return None

        salt = dec_material.encMsgV3[:32]
        counter_iv = dec_material.encMsgV3[32:]

        key = PBKDF2(self._bkey, salt, Decryptor.dklen, Decryptor.count,
                     Decryptor.prf, hmac_hash_module=None)

        counter_obj = Counter.new(128, initial_value=int.from_bytes(
            counter_iv, byteorder='big'), little_endian=False)

        decryptor = AES.new(key, mode=AES.MODE_CTR, counter=counter_obj)
        data_len = entry.stat().st_size
        with open(entry, 'rb') as entry_fd:
            for x in range(0, data_len, self.chunk_size):
                logging.debug('decrypting chunk %d of %s', x, entry)
                data = entry_fd.read(self.chunk_size)
                yield decryptor.decrypt(data) 
Example #4
Source File: rarfile.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def pbkdf2_sha256(password, salt, iters):
            """PBKDF2 with HMAC-SHA256"""
            ctx = pbkdf2.PBKDF2HMAC(hashes.SHA256(), 32, salt, iters, default_backend())
            return ctx.derive(password) 
Example #5
Source File: const_string_encryption.py    From Obfuscapk with MIT License 5 votes vote down vote up
def encrypt_string(self, string_to_encrypt: str) -> str:
        # This is needed to remove the escaping added by Python. For example, if we find in smali the instruction
        # const-string v0, "\"message\"" Android will treat it as "message" while in Python it's \"message\",
        # so we need to encrypt "message" and not \"message\" (we have to remove the unnecessary escaping, otherwise
        # the backslashes would by encrypted as part of the string).
        string_to_encrypt = string_to_encrypt.encode(errors='replace').decode('unicode_escape')

        key = PBKDF2(password=self.encryption_secret, salt=self.encryption_secret.encode(), dkLen=32, count=128)
        encrypted_string = hexlify(AES.new(key=key, mode=AES.MODE_ECB)
                                   .encrypt(pad(string_to_encrypt.encode(errors='replace'), AES.block_size))).decode()
        return encrypted_string 
Example #6
Source File: encryption.py    From airpyrt-tools with MIT License 5 votes vote down vote up
def _init_client_context(cls, key, iv):
		derived_key = KDF.PBKDF2(key, PBKDF_salt0, 16, 5)
		return _ACPEncryptionContext(derived_key, iv) 
Example #7
Source File: encryption.py    From airpyrt-tools with MIT License 5 votes vote down vote up
def _init_server_context(cls, key, iv):
		derived_key = KDF.PBKDF2(key, PBKDF_salt1, 16, 7)
		return _ACPEncryptionContext(derived_key, iv) 
Example #8
Source File: rar_define.py    From carpe with Apache License 2.0 5 votes vote down vote up
def pbkdf2_sha256(password, salt, iters):
            """PBKDF2 with HMAC-SHA256"""
            ctx = pbkdf2.PBKDF2HMAC(hashes.SHA256(), 32, salt, iters, default_backend())
            return ctx.derive(password) 
Example #9
Source File: rar_define.py    From carpe with Apache License 2.0 5 votes vote down vote up
def pbkdf2_sha256(password, salt, iters):
            """PBKDF2 with HMAC-SHA256"""
            return KDF.PBKDF2(password, salt, 32, iters, hmac_sha256) 
Example #10
Source File: jwt.py    From patzilla with GNU Affero General Public License v3.0 5 votes vote down vote up
def genkey(self, password, salt='', keysize=2048):

        master_key = PBKDF2(password, salt)

        def my_rand(n):
            # kluge: use PBKDF2 with count=1 and incrementing salt as deterministic PRNG
            my_rand.counter += 1
            return PBKDF2(master_key, "my_rand:%d" % my_rand.counter, dkLen=n, count=1)

        my_rand.counter = 0
        self.key = RSA.generate(keysize, randfunc=my_rand)

        return self.key 
Example #11
Source File: rarfile.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def pbkdf2_sha256(password, salt, iters):
            """PBKDF2 with HMAC-SHA256"""
            return KDF.PBKDF2(password, salt, 32, iters, hmac_sha256) 
Example #12
Source File: crypto.py    From PiBunny with MIT License 5 votes vote down vote up
def string_to_key(cls, string, salt, params):
        (iterations,) = unpack('>L', params or '\x00\x00\x10\x00')
        prf = lambda p, s: HMAC.new(p, s, SHA).digest()
        seed = PBKDF2(string, salt, cls.seedsize, iterations, prf)
        tkey = cls.random_to_key(seed)
        return cls.derive(tkey, 'kerberos') 
Example #13
Source File: test_KDF.py    From android_universal with MIT License 5 votes vote down vote up
def test1(self):
        # Test only for HMAC-SHA1 as PRF

        def prf_SHA1(p,s):
            return HMAC.new(p,s,SHA1).digest()

        def prf_SHA256(p,s):
            return HMAC.new(p,s,SHA256).digest()

        for i in range(len(self._testData)):
            v = self._testData[i]
            password = v[0]
            salt = t2b(v[1])
            out_len = v[2]
            iters = v[3]
            hash_mod = v[4]
            expected = t2b(v[5])

            if hash_mod is SHA1:
                res = PBKDF2(password, salt, out_len, iters)
                self.assertEqual(res, expected)

                res = PBKDF2(password, salt, out_len, iters, prf_SHA1)
                self.assertEqual(res, expected)
            else:
                res = PBKDF2(password, salt, out_len, iters, prf_SHA256)
                self.assertEqual(res, expected) 
Example #14
Source File: test_KDF.py    From android_universal with MIT License 5 votes vote down vote up
def test2(self):
        # Verify that prf and hmac_hash_module are mutual exclusive
        def prf_SHA1(p,s):
            return HMAC.new(p,s,SHA1).digest()

        self.assertRaises(ValueError, PBKDF2, b("xxx"), b("yyy"), 16, 100,
                          prf=prf_SHA1, hmac_hash_module=SHA1) 
Example #15
Source File: test_KDF.py    From android_universal with MIT License 5 votes vote down vote up
def test3(self):
        # Verify that hmac_hash_module works like prf

        password = b("xxx")
        salt = b("yyy")

        for hashmod in (MD5, SHA1, SHA224, SHA256, SHA384, SHA512):

            pr1 = PBKDF2(password, salt, 16, 100,
                         prf=lambda p, s: HMAC.new(p,s,hashmod).digest())
            pr2 = PBKDF2(password, salt, 16, 100, hmac_hash_module=hashmod)

            self.assertEqual(pr1, pr2) 
Example #16
Source File: test_KDF.py    From android_universal with MIT License 5 votes vote down vote up
def test4(self):
        # Verify that PBKDF2 can take bytes or strings as password or salt
        k1 = PBKDF2("xxx", b("yyy"), 16, 10)
        k2 = PBKDF2(b("xxx"), b("yyy"), 16, 10)
        self.assertEqual(k1, k2)

        k1 = PBKDF2(b("xxx"), "yyy", 16, 10)
        k2 = PBKDF2(b("xxx"), b("yyy"), 16, 10)
        self.assertEqual(k1, k2) 
Example #17
Source File: Crypt.py    From dnsfilexfer with MIT License 5 votes vote down vote up
def _gen_keys(self, salt):
        keys = PBKDF2(self.secret, salt, BLOCK_SIZE * 2)
        key_enc = keys[0:BLOCK_SIZE]
        key_auth = keys[BLOCK_SIZE:]

        return key_enc, key_auth 
Example #18
Source File: crypto.py    From cracke-dit with MIT License 5 votes vote down vote up
def string_to_key(cls, string, salt, params):
        (iterations,) = unpack('>L', params or '\x00\x00\x10\x00')
        prf = lambda p, s: HMAC.new(p, s, SHA).digest()
        seed = PBKDF2(string, salt, cls.seedsize, iterations, prf)
        tkey = cls.random_to_key(seed)
        return cls.derive(tkey, 'kerberos') 
Example #19
Source File: res_string_encryption.py    From Obfuscapk with MIT License 5 votes vote down vote up
def encrypt_string(self, string_to_encrypt: str) -> str:
        # This is needed to remove the escaping added by Python. For example, if we find in string resources
        # the string "\"message\"" Android will treat it as "message" while in Python it's \"message\", so we
        # need to encrypt "message" and not \"message\" (we have to remove the unnecessary escaping, otherwise
        # the backslashes would by encrypted as part of the string).
        string_to_encrypt = string_to_encrypt.encode(errors='replace').decode('unicode_escape')

        key = PBKDF2(password=self.encryption_secret, salt=self.encryption_secret.encode(), dkLen=32, count=128)
        encrypted_string = hexlify(AES.new(key=key, mode=AES.MODE_ECB)
                                   .encrypt(pad(string_to_encrypt.encode(errors='replace'), AES.block_size))).decode()
        return encrypted_string 
Example #20
Source File: rarfile.py    From Lector with GNU General Public License v3.0 5 votes vote down vote up
def pbkdf2_sha256(password, salt, iters):
            """PBKDF2 with HMAC-SHA256"""
            ctx = pbkdf2.PBKDF2HMAC(hashes.SHA256(), 32, salt, iters, default_backend())
            return ctx.derive(password) 
Example #21
Source File: rarfile.py    From Lector with GNU General Public License v3.0 5 votes vote down vote up
def pbkdf2_sha256(password, salt, iters):
            """PBKDF2 with HMAC-SHA256"""
            return KDF.PBKDF2(password, salt, 32, iters, hmac_sha256) 
Example #22
Source File: crypto.py    From CVE-2017-7494 with GNU General Public License v3.0 5 votes vote down vote up
def string_to_key(cls, string, salt, params):
        (iterations,) = unpack('>L', params or '\x00\x00\x10\x00')
        prf = lambda p, s: HMAC.new(p, s, SHA).digest()
        seed = PBKDF2(string, salt, cls.seedsize, iterations, prf)
        tkey = cls.random_to_key(seed)
        return cls.derive(tkey, 'kerberos') 
Example #23
Source File: browsercookie.py    From transistor with MIT License 5 votes vote down vote up
def _darwin_key(self, salt, length):
        """
        return key if sys.platform == 'darwin'
        :return: PBKDF2 instance
        """
        # running Chrome on OSX
        my_pass = keyring.get_password('Chrome Safe Storage', 'Chrome')
        my_pass = my_pass.encode('utf8')
        iterations = 1003
        key = PBKDF2(my_pass, salt, length, iterations)
        return key 
Example #24
Source File: browsercookie.py    From transistor with MIT License 5 votes vote down vote up
def _linux_key(self, salt, length):
        """
        return key if sys.platform == 'darwin'
        :return: PBKDF2 instance
        """
        # running Chrome on Linux
        my_pass = 'peanuts'.encode('utf8')
        iterations = 1
        key = PBKDF2(my_pass, salt, length, iterations)
        return key 
Example #25
Source File: __init__.py    From lykops with Apache License 2.0 5 votes vote down vote up
def _create_key(b_password, b_salt, keylength, ivlength):
        hash_function = SHA256

        pbkdf2_prf = lambda p, s: HMAC.new(p, s, hash_function).digest()

        b_derivedkey = PBKDF2(
            b_password,
            b_salt,
            dkLen=(2 * keylength) + ivlength,
            count=10000,
            prf=pbkdf2_prf)
        return b_derivedkey 
Example #26
Source File: file.py    From keyrings.alt with MIT License 5 votes vote down vote up
def _create_cipher(self, password, salt, IV):
        """
        Create the cipher object to encrypt or decrypt a payload.
        """
        from Crypto.Protocol.KDF import PBKDF2
        from Crypto.Cipher import AES

        pw = PBKDF2(password, salt, dkLen=self.block_size)
        return AES.new(pw[: self.block_size], AES.MODE_CFB, IV) 
Example #27
Source File: rncryptor.py    From RNCryptor-python with MIT License 5 votes vote down vote up
def _pbkdf2(self, password, salt, iterations=10000, key_length=32):
        return KDF.PBKDF2(password, salt, dkLen=key_length, count=iterations, prf=self._prf) 
Example #28
Source File: rarfile.py    From addon with GNU General Public License v3.0 5 votes vote down vote up
def pbkdf2_sha256(password, salt, iters):
            """PBKDF2 with HMAC-SHA256"""
            ctx = pbkdf2.PBKDF2HMAC(hashes.SHA256(), 32, salt, iters, default_backend())
            return ctx.derive(password) 
Example #29
Source File: rarfile.py    From addon with GNU General Public License v3.0 5 votes vote down vote up
def pbkdf2_sha256(password, salt, iters):
            """PBKDF2 with HMAC-SHA256"""
            return KDF.PBKDF2(password, salt, 32, iters, hmac_sha256) 
Example #30
Source File: ffsend.py    From ffsend with Mozilla Public License 2.0 5 votes vote down vote up
def derive_auth_key(secret, password=None, url=None):
    if password is None:
        return hkdf(64, secret, info=b'authentication')
    else:
        return PBKDF2(password.encode('utf8'), url.encode('utf8'), 64, 100,
                      lambda x, y: hmac.new(x, y, sha256).digest())