Ejemplo n.º 1
0
    def test2(self):
        """From draft-josefsson-scrypt-kdf-01, Chapter 10"""

        output_1 = t2b("""
        55 ac 04 6e 56 e3 08 9f ec 16 91 c2 25 44 b6 05
        f9 41 85 21 6d de 04 65 e6 8b 9d 57 c2 0d ac bc
        49 ca 9c cc f1 79 b6 45 99 16 64 b3 9d 77 ef 31
        7c 71 b8 45 b1 e3 0b d5 09 11 20 41 d3 a1 97 83
        """)

        output_2 = t2b("""
        4d dc d8 f6 0b 98 be 21 83 0c ee 5e f2 27 01 f9
        64 1a 44 18 d0 4c 04 14 ae ff 08 87 6b 34 ab 56
        a1 d4 25 a1 22 58 33 54 9a db 84 1b 51 c9 b3 17
        6a 27 2b de bb a1 d0 78 47 8f 62 b3 97 f3 3c 8d
        """)

        prf_hmac_sha256 = lambda p, s: HMAC.new(p, s, SHA256).digest()

        output = PBKDF2(b("passwd"), b("salt"), 64, 1, prf=prf_hmac_sha256)
        self.assertEqual(output, output_1)

        output = PBKDF2(b("Password"),
                        b("NaCl"),
                        64,
                        80000,
                        prf=prf_hmac_sha256)
        self.assertEqual(output, output_2)
Ejemplo n.º 2
0
def derive_password(password, salt):

    PBKDF2(password,
        b'D8VxSmTZt2E2YV454mkqAY5e', # Noncompliant {{Make this salt unpredictable.}}
#       ^^^^^^^^^^^^^^^^^^^^^^^^^^^
        32, count=100000
    )

    key = scrypt(password, b'D8VxSmTZt2E2YV454mkqAY5e', 32, N=2**14, r=8, p=1) # Noncompliant {{Make this salt unpredictable.}}
#                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
    key = bcrypt(password, 12, b'D8VxSmTZt2E2YV45') # Noncompliant {{Make this salt unpredictable.}}
#                              ^^^^^^^^^^^^^^^^^^^


    PBKDF2(password, salt, # Compliant
        32, count=100000
    )

    salt_ = get_random_bytes(32)
    PBKDF2(password, salt_, # Compliant
        32, count=100000,
    )

    key = scrypt(password, salt_, 32, N=2**14, r=8, p=1) # Compliant

    salt_16 = get_random_bytes(16)
    key = bcrypt(password, 12, salt_16) # Compliant
Ejemplo n.º 3
0
    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)
Ejemplo n.º 4
0
    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)
Ejemplo n.º 5
0
    def get_cookies(self):
        salt = b"saltysalt"
        length = 16
        if sys.platform == "darwin":
            # 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)

        elif sys.platform.startswith("linux"):
            # running Chrome on Linux
            my_pass = "******".encode("utf8")
            iterations = 1
            key = PBKDF2(my_pass, salt, length, iterations)

        elif sys.platform == "win32":
            # Must be win32 (on win32, all chrome cookies are encrypted)
            try:
                import win32crypt
            except ImportError:
                raise BrowserCookieError(
                    "win32crypt must be available to decrypt Chrome cookie on Windows"
                )
            path = r"%LocalAppData%\Google\Chrome\User Data\Local State"
            path = os.path.expandvars(path)
            with open(path, "r", encoding="utf-8") as file:
                encrypted_key = json.loads(
                    file.read())["os_crypt"]["encrypted_key"]
            encrypted_key = base64.b64decode(encrypted_key)  # Base64 decoding
            encrypted_key = encrypted_key[5:]
            key = win32crypt.CryptUnprotectData(encrypted_key, None, None,
                                                None, 0)[1]
        else:
            raise BrowserCookieError("Unsupported operating system: " +
                                     sys.platform)

        for cookie_file in self.cookie_files:
            with create_local_copy(cookie_file) as tmp_cookie_file:
                con = sqlite3.connect(tmp_cookie_file)
                cur = con.cursor()
                cur.execute('SELECT value FROM meta WHERE key = "version";')
                version = int(cur.fetchone()[0])
                query = "SELECT host_key, path, is_secure, expires_utc, name, value, encrypted_value FROM cookies;"
                if version < 10:
                    query = query.replace("is_", "")
                cur.execute(query)
                for item in cur.fetchall():
                    host, path, secure, expires, name = item[:5]
                    value = self._decrypt(item[5], item[6], key=key)
                    yield create_cookie(host, path, secure, expires, name,
                                        value)
                con.close()
Ejemplo n.º 6
0
    def test1(self):
        # Test only for HMAC-SHA1 as PRF

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

        for i in xrange(len(self._testData)):
            v = self._testData[i]
            res = PBKDF2(v[0], t2b(v[1]), v[2], v[3])
            res2 = PBKDF2(v[0], t2b(v[1]), v[2], v[3], prf)
            self.assertEqual(res, t2b(v[4]))
            self.assertEqual(res, res2)
Ejemplo n.º 7
0
    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)
Ejemplo n.º 8
0
    def get_cookies(self):
        salt = b'saltysalt'
        length = 16
        if sys.platform == 'darwin':
            # 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)

        elif sys.platform.startswith('linux'):
            # running Chrome on Linux
            my_pass = '******'.encode('utf8')
            iterations = 1
            key = PBKDF2(my_pass, salt, length, iterations)

        elif sys.platform == 'win32':
            path = r'%LocalAppData%\Google\Chrome\User Data\Local State'
            path = os.path.expandvars(path)
            with open(path, 'r') as file:
                encrypted_key = json.loads(
                    file.read())['os_crypt']['encrypted_key']
            encrypted_key = base64.b64decode(encrypted_key)  # Base64 decoding
            encrypted_key = encrypted_key[5:]  # Remove DPAPI
            key = win32crypt.CryptUnprotectData(encrypted_key, None, None,
                                                None, 0)[1]  # Decrypt key
        else:
            raise BrowserCookieError('Unsupported operating system: ' +
                                     sys.platform)

        for cookie_file in self.cookie_files:
            with create_local_copy(cookie_file) as tmp_cookie_file:
                con = sqlite3.connect(tmp_cookie_file)
                cur = con.cursor()
                cur.execute('SELECT value FROM meta WHERE key = "version";')
                version = int(cur.fetchone()[0])
                query = 'SELECT host_key, path, is_secure, expires_utc, name, value, encrypted_value FROM cookies;'
                if version < 10:
                    query = query.replace('is_', '')
                cur.execute(query)
                for item in cur.fetchall():
                    host, path, secure, expires, name = item[:5]
                    value = self._decrypt(item[5],
                                          item[6],
                                          item[4],
                                          item[1],
                                          key=key)
                    yield create_cookie(host, path, secure, expires, name,
                                        value)
                con.close()
Ejemplo n.º 9
0
def decrypt(pass_phrase, cipher_text):
    """
    Decrypt encrypted data with provided pass phrase

    :param pass_phrase: Pass phrase
    :type pass_phrase: String
    :param cipher_text: Encrypted data
    :type cipher_text: String
    :return: Decrypted data
    :rtype: String
    """
    mode = AES.MODE_CBC
    block_size = AES.block_size
    salt, initialization_vector, body = cipher_text.split('.')

    body = b64decode(body.encode('utf-8'))
    initialization_vector = b64decode(initialization_vector.encode('utf-8'))
    salt = b64decode(salt.encode('utf-8'))

    key = PBKDF2(pass_phrase, salt)
    cipher = AES.new(key, mode, initialization_vector)

    try:
        body = Padding.unpad(cipher.decrypt(body), block_size).decode('utf-8')
    except ValueError:
        # most likely a padding error which suggests incorrect password
        raise click.UsageError('Password incorrect')
    return body
Ejemplo n.º 10
0
def entropy_to_privkey(entropy: bytes) -> bytes:
    priv_key = PBKDF2(entropy,
                      entropy,
                      dkLen=32,
                      count=PBKDF_ITERATIONS,
                      prf=lambda p, s: HMAC.new(p, s, SHA256).digest())
    return priv_key
Ejemplo n.º 11
0
def decrypt(secretkey, params):
    iv = b64decode(params['iv'])
    salt = b64decode(params['salt'])
    #~ keylen = params.get('ks', 128) // 8 # FIXME use somewhere?
    taglen = params.get('ts', 64) // 8
    iterations = params.get('iter', 1000)
    data = b64decode(params['ct'])
    ciphertext = data[:-taglen]
    tag = data[-taglen:]

    if params.get('adata'):
        raise NotImplementedError(
            'authenticated data support is not implemented')

    iv = trunc_iv(iv, ciphertext, taglen)

    hash_func = lambda k, s: HMAC.new(k, s, SHA256).digest()
    key = PBKDF2(secretkey, salt=salt, count=iterations, prf=hash_func)

    mode_str = params.get('mode', 'ccm')
    mode = dict(ccm=AES.MODE_CCM)[mode_str]
    if mode_str == 'ccm':
        cipher = AES.new(key, mode=AES.MODE_CCM, nonce=iv, mac_len=taglen)
    else:
        cipher = AES.new(key, mode=mode, iv=iv)
    decrypted = cipher.decrypt_and_verify(ciphertext, tag)
    return decrypted
 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)
Ejemplo n.º 13
0
def encrypt(content: bytes, password: str) -> str:
    """
    Encrypt html content, act like `staticrypt`.

    Args:
        content: html content bytes
        password: password to encrypt and decrypt

    Returns:
        The encrypted contend
    """

    salt = urandom(16)
    iv = urandom(16)
    key = PBKDF2(password=password, salt=salt, dkLen=32, count=1000)
    cryptor = AES.new(key, AES.MODE_CBC, iv)

    pkcs7_content = pad(content, AES.block_size)

    aes_encrypted_bytes = b64encode(cryptor.encrypt(pkcs7_content))

    aes_encrypted_content = (salt.hex() + iv.hex() +
                             aes_encrypted_bytes.decode("utf-8"))

    hmac_signature = hmac.new(key=sha256(
        password.encode("utf-8")).hexdigest().encode("utf-8"),
                              msg=aes_encrypted_content.encode("utf-8"),
                              digestmod=sha256).hexdigest()

    return hmac_signature + aes_encrypted_content
Ejemplo n.º 14
0
    def __init__(self):

        # init base class
        super().__init__()

        self.login_db_path = f"/home/{getuser()}/.config/google-chrome/Default/Login Data"
        self.tmp_login_db_path = f"/home/{getuser()}/.config/google-chrome/Default/Login_tmp"

        if os.path.exists(self.login_db_path):
            shutil.copy2(
                self.login_db_path, self.tmp_login_db_path
            )  # making a temp copy since login data db is locked while chrome is running
        else:
            print("It seems that no chrome browser is installed! Exiting...")
            exit(1)

        self.iv = b' ' * 16
        self.password = '******'.encode('utf8')

        bus = secretstorage.dbus_init()
        collection = secretstorage.get_default_collection(bus)
        for item in collection.get_all_items():
            if item.get_label() == 'Chrome Safe Storage':
                self.password = item.get_secret()
                break

        self.key = PBKDF2(password=self.password,
                          salt=b'saltysalt',
                          dkLen=16,
                          count=1)
        self.cipher = AES.new(self.key, AES.MODE_CBC, IV=self.iv)
        self.bytechars = [
            b'\x01', b'\x02', b'\x03', b'\x04', b'\x05', b'\x06', b'\x07',
            b'\x08', b'\x09'
        ]
Ejemplo n.º 15
0
    def handleLogin(self):
        sd = SAHDao()
        res = sd.select_item2()
        res2 = sd.select_item_pw()
        res_salt = sd.select_item_salt()
        tmp_dict = {}
        salt_list = []

        for i in range(len(res)):
            dict1 = {res[i][0]: res2[i][0]}
            tmp_dict.update(dict1)
            salt_list.append(res_salt[i][0])

        dict_list_id = list(tmp_dict.keys())
        dict_list_pw = list(tmp_dict.values())
        print(dict_list_pw)

        for i in range(len(dict_list_id)):
            dict_list_id[i] = dict_list_id[i].strip()

        salt_index = dict_list_id.index(self.id_name.text())
        salt_res_2 = salt_list[salt_index]

        if self.id_name.text() in dict_list_id:
            password = self.pw.text()
            salt = base64.urlsafe_b64decode(salt_res_2)
            pb = PBKDF2(password, salt, 128, 10000, hmac_hash_module=SHA1)
            key = base64.b64encode(pb).decode('utf-8')
            if key in dict_list_pw:
                self.accept()
            else:
                QtWidgets.QMessageBox.warning(self, '비밀번호 오류', '비밀번호가 틀렸습니다.')
        else:
            QtWidgets.QMessageBox.warning(self, '아이디오류', '아이디가 틀렸습니다.')
Ejemplo n.º 16
0
def decryptStr(base64Ciphertext, password):

    try:
        encrypted = base64.b64decode(base64Ciphertext, validate=True)
    except binascii.Error:
        encrypted = base64Ciphertext

    # Extract Variables for Decryption
    b_salt = encrypted[:AES.block_size]
    b_nonce = encrypted[AES.block_size:ALGORITHM_KEY_SIZE]
    b_associatedText = encrypted[:AES.block_size]
    b_tag = encrypted[-16:]
    b_ciphertext = encrypted[ALGORITHM_KEY_SIZE:-AES.block_size]

    # Derive the key using PBKDF2.
    key = PBKDF2(password=password,
                 salt=b_salt,
                 dkLen=ALGORITHM_KEY_SIZE,
                 count=PBKDF2_ITERATIONS)

    # Create the cipher.
    cipher = AES.new(key, mode=AES.MODE_GCM, nonce=b_nonce)
    cipher.update(b_associatedText)

    # Decrypt
    plaintext = cipher.decrypt(b_ciphertext)

    return plaintext
Ejemplo n.º 17
0
def generate_aes_encryption_key(password: str,
                                salt: bytes = None) -> Tuple[bytes, bytes]:
    """ uses PBKDF2 with SHA256 HMAC to derive a 32-byte encryption key from the provided password """
    if salt is None:
        salt = get_random_bytes(8)
    return PBKDF2(password, salt, 32, count=1000000,
                  hmac_hash_module=SHA256), salt
Ejemplo n.º 18
0
def _pbkdf2(password, salt, n_bytes, count):
    # the form of the prf below is taken from the code for PBKDF2
    return PBKDF2(password,
                  salt,
                  dkLen=n_bytes,
                  count=count,
                  prf=lambda p, s: HMAC.new(p, s, HASH).digest())
Ejemplo n.º 19
0
def encrypt(plaintext):
    iv = urandom(16)
    salt = urandom(8)
    iterations = 1000
    ks = 128
    ts = 64

    hash_func = lambda k, s: HMAC.new(k, s, SHA256).digest()
    password = b64encode(urandom(32))
    key = PBKDF2(password, salt=salt, count=iterations, prf=hash_func)

    smalliv = trunc_iv(iv, plaintext, 0)

    cipher = AES.new(key, mode=AES.MODE_CCM, nonce=smalliv, mac_len=ts // 8)
    ciphertext = b''.join(cipher.encrypt_and_digest(plaintext))

    # OrderedDict because 0bin is a piece of shit requiring "iv" as the first key
    return password.decode('ascii'), OrderedDict([
        ('iv', b64encode(iv).decode('ascii')),
        ('v', 1),
        ('iter', iterations),
        ('ks', ks),
        ('ts', ts),
        ('mode', 'ccm'),
        ('adata', ''),
        ('cipher', 'aes'),
        ('salt', b64encode(salt).decode('ascii')),
        ('ct', b64encode(ciphertext).decode('ascii')),
    ])
Ejemplo n.º 20
0
def decode_note():
    entered_passwd = request.form[DECRYPT_PASSWD_FIELD_ID]
    note_id = request.form[NOTE_ID_FIELD_ID]

    note = Note.query.filter_by(id=note_id).first()
    iv = b64decode(note.iv)
    encrypted_note = b64decode(note.note_content)
    file_name = None

    try:
        key = PBKDF2(entered_passwd.encode('utf-8'), note.salt)
        cipher = AES.new(key, AES.MODE_CBC, iv)
        decrypted_note = unpad(cipher.decrypt(encrypted_note),
                               AES.block_size).decode("utf-8")
        if note.file:
            file = File.query.filter_by(file_uuid=note.file).first()
            file_name = file.file_name
        return jsonify({
            'message': 'Poprawnie odszyfrowano notatkę.',
            'decrypted_note_content': decrypted_note,
            'file_name': file_name,
            'status': 200
        }), 200
    except ValueError:
        return jsonify({'message': 'Błędne hasło.', 'status': 400}), 400
Ejemplo n.º 21
0
def encrypt(pass_phrase, data):
    """
    Encrypt data using a pass phrase

    :param pass_phrase: Pass phrase to encrypt data with
    :type pass_phrase: String
    :param data: Data to encrypt
    :type data: String
    :return: Formatted string that contains salt, iv and encrypted message
    :rtype: String
    """
    mode = AES.MODE_CBC
    block_size = AES.block_size
    salt = get_random_bytes(8)
    key = PBKDF2(pass_phrase, salt)
    body = Padding.pad(data.encode('utf-8'), block_size)
    initialization_vector = get_random_bytes(16)

    cipher = AES.new(key, mode, initialization_vector)

    # Now reassign salt, iv and body with their base64 encoded counterparts
    salt = b64encode(salt).decode('utf-8')
    initialization_vector = b64encode(initialization_vector).decode('utf-8')
    body = b64encode(cipher.encrypt(body)).decode('utf-8')

    return '{0}.{1}.{2}'.format(salt, initialization_vector, body)
Ejemplo n.º 22
0
def _decrypt_aes_256_cbc_pbkdf2(
    ciphertext: bytes,
    password: str,
) -> bytes:
    """Decrypt an openssl encrypted bytestring:
    Cipher: AES256-CBC
    Salted: yes
    Key Derivation: PKBDF2, with SHA256 digest, 10000 cycles
    """
    SALT_LENGTH = 8
    KEY_LENGTH = 32
    IV_LENGTH = 16
    PBKDF2_CYCLES = 10_000

    salt = ciphertext[:SALT_LENGTH]
    raw_key = PBKDF2(password,
                     salt,
                     KEY_LENGTH + IV_LENGTH,
                     count=PBKDF2_CYCLES,
                     hmac_hash_module=SHA256)
    key, iv = raw_key[:KEY_LENGTH], raw_key[KEY_LENGTH:]

    decryption_suite = AES.new(key, AES.MODE_CBC, iv)
    decrypted_pkg = decryption_suite.decrypt(ciphertext[SALT_LENGTH:])

    return _strip_fill_bytes(decrypted_pkg)
Ejemplo n.º 23
0
 def __init__(self, entropy, IDString):
     sp = GetUserName() + b'+@#$%+' + IDString
     passwdData = encode(SHA256(sp), charMap2)
     salt = entropy
     key_iv = PBKDF2(passwdData, salt, count=0x800, dkLen=0x400)
     self.key = key_iv[0:32]
     self.iv = key_iv[32:48]
     self.crp.set_decrypt_key(self.key, self.iv)
Ejemplo n.º 24
0
def encode_text_from_note(text, password):
    salt = get_random_bytes(16)
    key = PBKDF2(password.encode('utf-8'), salt)
    utfText = text.encode('utf-8')
    aes = AES.new(key, AES.MODE_CBC)
    encryptedText = b64encode(aes.encrypt(pad(utfText, AES.block_size))).decode('utf-8')
    iv = b64encode(aes.iv).decode('utf-8')
    return encryptedText, iv, b64encode(salt).decode('utf-8')
Ejemplo n.º 25
0
    def _create_cipher(self, password, salt, IV):
        """
        Create the cipher object to encrypt or decrypt a payload.
        """
        from Cryptodome.Protocol.KDF import PBKDF2
        from Cryptodome.Cipher import AES

        pw = PBKDF2(password, salt, dkLen=self.block_size)
        return AES.new(pw[:self.block_size], AES.MODE_CFB, IV)
Ejemplo n.º 26
0
def encrypt_note_content(note_content, password):
    salt = get_random_bytes(16)
    key = PBKDF2(password.encode('utf-8'), salt)
    to_encrypt = note_content.encode('utf-8')

    cipher = AES.new(key, AES.MODE_CBC)
    encrypted_note_bytes = cipher.encrypt(pad(to_encrypt, AES.block_size))
    iv = b64encode(cipher.iv).decode('utf-8')
    encrypted_note = b64encode(encrypted_note_bytes).decode('utf-8')
    return encrypted_note, salt, iv
Ejemplo n.º 27
0
def decryptutil(password, result):
    b64 = json.loads(result)
    json_k = ['nonce', 'salt', 'ciphertext', 'tag']
    jv = {k: b64decode(b64[k]) for k in json_k}
    key = PBKDF2(password=password, salt=jv['salt'], count=1000)

    cipher = AES.new(key, AES.MODE_GCM, nonce=jv['nonce'])

    plaintext = cipher.decrypt_and_verify(jv['ciphertext'], jv['tag'])

    # A readable client socket has data
    sys.stdout.write(plaintext.decode("utf-8"))
Ejemplo n.º 28
0
def encrypt(key, plaintext):
    if key == '':
        return b64encode(plaintext.encode()).decode().replace('=', '')
    salt = get_random_bytes(8)
    iv = get_random_bytes(16)
    key = PBKDF2(key.encode(), salt, count=10000, dkLen=16, prf=prf)
    data, compression = zlib(plaintext)
    nonce = truncate_iv(iv, len(data) * 8, 64)
    cipher = AES.new(key, AES.MODE_CCM, nonce=nonce, mac_len=8)
    ciphertext, tag = cipher.encrypt_and_digest(data)
    return b64encode(salt + iv + ciphertext + tag +
                     compression).decode().replace('=', '')
Ejemplo n.º 29
0
Archivo: snc.py Proyecto: zyczyh/SNC
def AES_GCM_encrypt(data, password):
    salt = get_random_bytes(16)  # salt for generate key
    key = PBKDF2(password=password, salt=salt, dkLen=32)
    cipher = AES.new(key, AES.MODE_GCM)
    cipher.update(salt)
    ciphertext, tag = cipher.encrypt_and_digest(data)
    json_k = ['nonce', 'salt', 'ciphertext', 'tag']
    json_v = [
        b64encode(x).decode('utf-8')
        for x in [cipher.nonce, salt, ciphertext, tag]
    ]
    result = json.dumps(dict(zip(json_k, json_v)))
    return result.encode()
Ejemplo n.º 30
0
    def get_cookies(self):
        salt = b'saltysalt'
        length = 16
        if sys.platform == 'darwin':
            # 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)

        elif sys.platform.startswith('linux'):
            # running Chrome on Linux
            my_pass = '******'.encode('utf8')
            iterations = 1
            key = PBKDF2(my_pass, salt, length, iterations)

        elif sys.platform == 'win32':
            key = None
        else:
            raise BrowserCookieError('Unsupported operating system: ' +
                                     sys.platform)

        for cookie_file in self.cookie_files:
            with create_local_copy(cookie_file) as tmp_cookie_file:
                con = sqlite3.connect(tmp_cookie_file)
                cur = con.cursor()
                cur.execute('SELECT value FROM meta WHERE key = "version";')
                version = int(cur.fetchone()[0])
                query = 'SELECT host_key, path, is_secure, expires_utc, name, value, encrypted_value FROM cookies;'
                if version < 10:
                    query = query.replace('is_', '')
                cur.execute(query)
                for item in cur.fetchall():
                    host, path, secure, expires, name = item[:5]
                    value = self._decrypt(item[5], item[6], key=key)
                    yield create_cookie(host, path, secure, expires, name,
                                        value)
                con.close()