Exemple #1
0
    def test_bad_version(self):
        # test incorrect version of Fernet 0x91
        key = Fernet.generate_key()
        fernet = Fernet(key)

        ct = fernet.encrypt('Secret message!')
        ct = list(base64.urlsafe_b64decode(ct))     # decode ciphertext
        ct[0] = b'\x00'                             # change version
        ct = ''.join(ct)
        ct = base64.urlsafe_b64encode(ct)           # encode ciphertext

        with pytest.raises(InvalidToken) as e:
            fernet.decrypt(ct)
Exemple #2
0
    def test_Functionality_extensive(self):
        # extensively test the decrpytion(encryption(msg)) == msg
        key = Fernet.generate_key()
        fernet = Fernet(key)

        # decrypt(encrypt(msg)) == msg
        for i in xrange(100):
            for l in range(20):
                msg = os.urandom(l)
                assert fernet.decrypt(fernet.encrypt(msg)) == msg
Exemple #3
0
def decrypt(filename, key):
    print("Decrypting...")

    f = Fernet(key)
    with open(filename, "rb") as fr:
        # read the encrypted data
        encrypted_data = fr.read()
    # decrypt data
    decrypted_data = f.decrypt(encrypted_data)
    # write the original file
    with open(filename, "wb") as fl:
        fl.write(decrypted_data)

    print("Finished")
    sys.exit()
Exemple #4
0
def test_fernet():
    current_time = int(time.time())
    iv = os.urandom(16)
    from cryptography.fernet import Fernet as CFernet

    salt = os.urandom(16)
    key = pbkdf2_hmac('sha256', b"password", salt, 100000, dklen=32)
    ckey = base64.urlsafe_b64encode(key)
    cfernet = CFernet(ckey)
    ccipher = cfernet._encrypt_from_parts(b"Secret message!", current_time, iv)

    fernet = Fernet(ckey)
    cipher = fernet._encrypt_from_parts(b"Secret message!", current_time, iv)
    assert cipher == ccipher
    ctext = cfernet.decrypt(ccipher)
    text = fernet.decrypt(cipher)

    assert ctext == text
Exemple #5
0
class Fernet2(object):
    def __init__(self, key, backend=None):
        if backend is None:
            backend = default_backend()

        # initialize a fernet object
        self._f = Fernet(key, backend=backend)

        key = base64.urlsafe_b64decode(key)
        if len(key) != 32:
            raise ValueError(
                "Fernet2 key must be 32 url-safe base64-encoded bytes.")

        h0 = HMAC(key, hashes.SHA256(), backend=backend)
        h1 = HMAC(key, hashes.SHA256(), backend=backend)
        #
        h0.update(b"0")
        h1.update(b"1")
        k0 = h0.finalize()[:16]
        k1 = h1.finalize()[:16]

        self._signing_key = k0
        self._encryption_key = k1
        self._backend = backend

    @classmethod
    def generate_key(cls):
        return base64.urlsafe_b64encode(os.urandom(32))

    def encrypt(self, data, adata=""):
        # removed current time
        iv = os.urandom(16)
        return self._encrypt_from_parts(data, iv, adata)

    def _encrypt_from_parts(self, data, iv, adata=""):
        if not isinstance(data, bytes):
            raise TypeError("data must be bytes.")

        padder = padding.PKCS7(algorithms.AES.block_size).padder()
        padded_data = padder.update(data) + padder.finalize()
        encryptor = Cipher(algorithms.AES(self._encryption_key), modes.CBC(iv),
                           self._backend).encryptor()
        # ctx = AES( iv || msg )
        ctx = encryptor.update(padded_data) + encryptor.finalize()
        basic_parts = (b"\x81" + iv + ctx)
        # print(str(len(basic_parts)), "basic_parts_len == ", basic_parts)
        # print("iv = " + str(len(iv)), iv)
        # print(str(len(ctx)), "ctx == ", ctx)
        # print("adata == " , len(adata), adata)
        h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
        h.update(basic_parts + adata)
        # tag = HMAC( 0x81 || iv || ctx )
        tag = h.finalize()
        # print("tag = " , len(tag))
        return base64.urlsafe_b64encode(basic_parts + tag)

    def decrypt(self, token, ttl=None, adata=""):
        if not isinstance(token, bytes):
            raise TypeError("token must be bytes.")
        # print("token = ", token)

        try:
            data = base64.urlsafe_b64decode(token)
        except (TypeError, binascii.Error):
            raise InvalidToken
        # print("data = ", data)
        if not data or six.indexbytes(data, 0) == 0x80:
            print("80 version\n")
            # TODO: if 80:
            try:
                msg = self._f.decrypt(token, ttl)
                return msg
            except:
                raise InvalidToken

        elif not data or six.indexbytes(data, 0) == 0x81:
            # print("81 version\n")

            ############ VERIFYING adata
            # print("data = " + str(len(data)), data)
            h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
            basic_parts = data[:-32]
            basic_adata = basic_parts + bytes(adata)
            # print("==================", base64.urlsafe_b64decode(base64.urlsafe_b64encode(adata)))
            h.update(basic_adata)
            # print("basic_parts_len = " + str(len(basic_parts)), basic_parts)

            # print("basic_adata = " + str(len(basic_adata)), basic_adata)
            # print("adata = " , len(adata), adata)
            try:
                h.verify(data[-32:])
            except InvalidSignature:
                raise InvalidToken

            ################ signature stuff from fernet.py
            # h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
            # h.update(data[:-32]) # get everything from data except for last 32 bytes
            # # print(h.update(data[:-32]))
            # try:
            #     # verifying signature with the last 32 bytes
            #     h.verify(data[-32:])
            # except InvalidSignature:
            #     raise InvalidToken
            ################ END-OF signature stuff from fernet.py

            # iv = data[9:25]
            iv = data[1:17]
            # print("iv == " + str(len(iv)), iv)
            # find out associated data in data
            # try satement, if adata_to_get = adata
            ciphertext = data[17:-32]
            decryptor = Cipher(algorithms.AES(self._encryption_key),
                               modes.CBC(iv), self._backend).decryptor()
            plaintext_padded = decryptor.update(ciphertext)
            try:
                plaintext_padded += decryptor.finalize()
            except ValueError:
                raise InvalidToken
            unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()

            unpadded = unpadder.update(plaintext_padded)
            try:
                unpadded += unpadder.finalize()
            except ValueError:
                raise InvalidToken
            return unpadded

        else:
            raise InvalidToken
Exemple #6
0
def decryptMessage(data, key):
    f = Fernet(key)
    return f.decrypt(data).decode()
Exemple #7
0
class Fernet2(object):
    def __init__(self, key, backend=None):
        if backend is None:
            backend = default_backend()

        # initialize a fernet object
        self._f = Fernet(key, backend=backend)

        key = base64.urlsafe_b64decode(key)
        if len(key) != 32:
            raise ValueError(
                "Fernet2 key must be 32 url-safe base64-encoded bytes."
            )

        h0 = HMAC(key, hashes.SHA256(), backend=backend)
        h1 = HMAC(key, hashes.SHA256(), backend=backend)
        # 
        h0 .update(b"0")
        h1 .update(b"1")
        k0 = h0.finalize()[:16]
        k1 = h1.finalize()[:16]

        self._signing_key = k0
        self._encryption_key = k1
        self._backend = backend

    @classmethod
    def generate_key(cls):
        return base64.urlsafe_b64encode(os.urandom(32))

    def encrypt(self, data, adata=""):
        # removed current time
        iv = os.urandom(16)
        return self._encrypt_from_parts(data, iv, adata)

    def _encrypt_from_parts(self, data, iv, adata=""):
        if not isinstance(data, bytes):
            raise TypeError("data must be bytes.")

        padder = padding.PKCS7(algorithms.AES.block_size).padder()
        padded_data = padder.update(data) + padder.finalize()
        encryptor = Cipher(
            algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend
        ).encryptor()
        # ctx = AES( iv || msg )
        ctx = encryptor.update(padded_data) + encryptor.finalize()
        basic_parts = (
            b"\x81" + iv + ctx
        )
        # print(str(len(basic_parts)), "basic_parts_len == ", basic_parts)
        # print("iv = " + str(len(iv)), iv)
        # print(str(len(ctx)), "ctx == ", ctx)
        # print("adata == " , len(adata), adata)
        h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
        h.update(basic_parts+adata)
        # tag = HMAC( 0x81 || iv || ctx )
        tag = h.finalize()
        # print("tag = " , len(tag))
        return base64.urlsafe_b64encode( basic_parts + tag)

    def decrypt(self, token, ttl=None, adata=""):
        if not isinstance(token, bytes):
            raise TypeError("token must be bytes.")
        # print("token = ", token)

        try:
            data = base64.urlsafe_b64decode(token)
        except (TypeError, binascii.Error):
            raise InvalidToken
        # print("data = ", data)
        if not data or six.indexbytes(data, 0) == 0x80:
            print("80 version\n")
            # TODO: if 80:
            try:
                msg = self._f.decrypt(token, ttl)
                return msg
            except:
                raise InvalidToken

        elif not data or six.indexbytes(data, 0) == 0x81:
            # print("81 version\n")

            ############ VERIFYING adata
            # print("data = " + str(len(data)), data)
            h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
            basic_parts = data[:-32]
            basic_adata = basic_parts + bytes(adata)
            # print("==================", base64.urlsafe_b64decode(base64.urlsafe_b64encode(adata)))
            h.update(basic_adata)
            # print("basic_parts_len = " + str(len(basic_parts)), basic_parts)

            # print("basic_adata = " + str(len(basic_adata)), basic_adata)
            # print("adata = " , len(adata), adata)
            try:
                h.verify(data[-32:])
            except InvalidSignature:
                raise InvalidToken

            ################ signature stuff from fernet.py
            # h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend)
            # h.update(data[:-32]) # get everything from data except for last 32 bytes
            # # print(h.update(data[:-32]))
            # try:
            #     # verifying signature with the last 32 bytes
            #     h.verify(data[-32:])
            # except InvalidSignature:
            #     raise InvalidToken
            ################ END-OF signature stuff from fernet.py

            # iv = data[9:25]
            iv = data[1:17]
            # print("iv == " + str(len(iv)), iv)
            # find out associated data in data
            # try satement, if adata_to_get = adata
            ciphertext = data[17:-32]
            decryptor = Cipher(
                algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend
            ).decryptor()
            plaintext_padded = decryptor.update(ciphertext)
            try:
                plaintext_padded += decryptor.finalize()
            except ValueError:
                raise InvalidToken
            unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()

            unpadded = unpadder.update(plaintext_padded)
            try:
                unpadded += unpadder.finalize()
            except ValueError:
                raise InvalidToken
            return unpadded

        else:
            raise InvalidToken
Exemple #8
0
def decrypt():
    file = open('encrypted.txt', 'rb')
    encrypted = file.read()
    f = Fernet(key)
    decrypted = f.decrypt(encrypted)
    print(decrypted.decode('utf-8'))
Exemple #9
0
# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

with open("../challenge/0/0", "r") as f:
    s = f.readlines()[0]
# print(s[0])
s = s[::-1]
print(s)
s_overall.append("2")  # bit or byte

# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

f = Fernet(b'LgCqSwV-aldTQzgqrF3ndMe4qG30KtTj-hUZ_PblzMI=')  # from notes.txt
with open("../challenge/1/1", "r") as fi:
    s = fi.readlines()[0]
s = f.decrypt(s.encode())
print(str(s))
s_overall.append("9")  # mimikatz

# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

with open("../challenge/2/2", "r") as fi:
    s = fi.readlines()[0]
    s = s.strip().encode()
with open("../challenge/2/keys", "r") as fi:
    for key in fi.readlines():
        key = key.strip().encode()
        try:
            f = Fernet(key)
            s = f.decrypt(s)
            break
Exemple #10
0
class Fernet2(object):
    def __init__(self, key, backend=None):
        if backend is None:
            backend = default_backend()
        try:
            self._fernet1 = Fernet(key, backend)
        except ValueError:
            self._fernet1 = None
        self._backend = backend

        key = base64.urlsafe_b64decode(key)
        hkey = hkdf.HKDF(algorithm=hashes.SHA256(), length=32,
                         salt='0'*16, info='', backend=backend)
        stretched_key = hkey.derive(key)
        self._signing_key, self._encryption_key = stretched_key[:16], stretched_key[16:]

    def SHA256hmac(self, key, data, sig=''):
        h = hmac.HMAC(key, hashes.SHA256(), backend=self._backend)
        h.update(data)
        if len(sig)>0:
            try:
                return h.verify(sig)
            except Exception as e:
                raise e
        else:
            return h.finalize()
        
    def _prf_hmac(self, key, data):
        out = self.SHA256hmac(key, data)
        while len(out)<len(data):
            out += self.SHA256hmac(key, out)
        return out[:len(data)]

    @classmethod
    def generate_key(cls):
        return base64.urlsafe_b64encode(os.urandom(32))

    def encrypt(self, data, associated_data=''):
        iv = os.urandom(16)
        return self._encrypt_from_parts(data, associated_data, iv)

    def _encrypt_from_parts(self, data, associated_data, iv):
        if not isinstance(data, bytes):
            raise TypeError("data must be bytes.")

        padder = padding.PKCS7(algorithms.AES.block_size).padder()
        padded_data = padder.update(data) + padder.finalize()
        encryptor = Cipher(
            algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend
        ).encryptor()
        ciphertext = encryptor.update(padded_data) + encryptor.finalize()

        # MAC:  version || ad || iv || ctx
        basic_parts = (
            b"\x81" + bytes(associated_data) + iv + ciphertext
        )

        tag = self.SHA256hmac(self._signing_key, basic_parts)

        # return: version || iv || ctx || tag
        return base64.urlsafe_b64encode(b"\x81" + iv + ciphertext + tag)

    def decrypt(self, ctxt, ttl=None, associated_data=''):
        if not isinstance(ctxt, bytes):
            raise TypeError("ctxt must be bytes.")

        try:
            data = base64.urlsafe_b64decode(ctxt)
        except (TypeError, binascii.Error):
            raise InvalidToken
        
        if not data:
            raise InvalidToken

        # return: version || iv || ctx || tag
        if six.indexbytes(data, 0) == 0x80:
            # This is a Fernet1 (old version) ctx, handle accordingly
            try:
                msg = self._fernet1.decrypt(ctxt, ttl=ttl)
            except Exception:
                raise InvalidToken
            return msg
        elif six.indexbytes(data, 0) != 0x81:
            raise InvalidToken
        assert not debug or not ttl, "You are calling new fernet with ttl values."

        # First, verify the tag
        basic_parts = (
            b"\x81" + bytes(associated_data) + data[1:-32]
        )

        try:
            self.SHA256hmac(self._signing_key, basic_parts, sig=data[-32:])
        except InvalidSignature:
            raise InvalidToken

        # Now decrypt the text
        # version (1-byte) || iv (16-byte) || ctx || tag (32-byte)
        iv = data[1:17]
        ciphertext = data[17:-32]
        decryptor = Cipher(
            algorithms.AES(self._encryption_key), modes.CBC(iv), self._backend
        ).decryptor()
        plaintext_padded = decryptor.update(ciphertext)
        try:
            plaintext_padded += decryptor.finalize()
        except ValueError:
            raise InvalidToken
        unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()

        unpadded = unpadder.update(plaintext_padded)
        try:
            unpadded += unpadder.finalize()
        except ValueError:
            raise InvalidToken
        return unpadded
Exemple #11
0
def decrypt(txt):

    txt = base64.urlsafe_b64decode(txt)
    cipher_suite = Fernet(settings.ENCRYPT_KEY)
    decoded_text = cipher_suite.decrypt(txt).decode("ascii")
    return decoded_text
Exemple #12
0
class ProjectConfig:
    """
    Read and write XML on profiles. Represents a database connection configuration.
    """

    SAVE_VERSION = VERSION_1_2  #: Version for saving

    #: Folder where to read/write project configs.
    profile_dir: str = filedir(
        config.value("ebcomportamiento/profiles_folder",
                     "%s/Pineboo/profiles" % Path.home()))

    version: VersionNumber  #: Version number for the profile read.
    fernet: Optional[Fernet]  #: Cipher used, if any.

    database: str  #: Database Name, file path to store it, or :memory:
    host: Optional[str]  #: DB server Hostname. None for local files.
    port: Optional[int]  #: DB server port. None for local files.
    username: Optional[str]  #: Database User login name.
    password: Optional[str]  #: Database User login password.
    type: str  #: Driver Type name to use when connecting
    project_password: str  #: Password to cipher when load/saving. Empty string for no ciphering.
    password_required: bool  #: True if a password is required to read data. (Was partially loaded.)
    description: str  #: Project name in GUI
    filename: str  #: File path to read / write this project from / to

    def __init__(
        self,
        database: Optional[str] = None,
        host: Optional[str] = None,
        port: Optional[int] = None,
        type: Optional[str] = None,
        username: Optional[str] = None,
        password: Optional[str] = None,
        load_xml: Optional[str] = None,
        connstring: Optional[str] = None,
        description: Optional[str] = None,
        filename: Optional[str] = None,
        project_password: str = "",
    ) -> None:
        """Initialize."""
        self.project_password = project_password
        self.password_required = False
        self.version = self.SAVE_VERSION
        self.fernet = None

        if connstring:
            username, password, type, host, port, database = self.translate_connstring(
                connstring)
        elif load_xml:
            self.filename = os.path.join(
                self.profile_dir,
                load_xml if load_xml.endswith("xml") else "%s.xml" % load_xml)
            self.load_projectxml()
            return
        if database is None:
            raise ValueError(
                "Database is mandatory. Or use load_xml / connstring params")
        if type is None:
            raise ValueError(
                "Type is mandatory. Or use load_xml / connstring params")
        self.database = database
        self.host = host
        self.port = port
        self.type = type
        self.username = username
        self.password = password
        self.description = description if description else "unnamed"
        if filename is None:
            file_basename = self.description.lower().replace(" ", "_")
            self.filename = os.path.join(self.profile_dir,
                                         "%s.xml" % file_basename)
        else:
            self.filename = os.path.join(self.profile_dir, filename)

    def get_uri(self, show_password: bool = False) -> str:
        """Get connection as an URI."""
        host_port = ""
        if self.host:
            host_port += self.host
        if self.port:
            host_port += ":%d" % self.port

        user_pass = ""
        if self.username:
            user_pass += self.username
        if self.password:
            if show_password:
                user_pass += ":%s" % self.password
            else:
                pass_bytes: bytes = hashlib.sha256(
                    self.password.encode()).digest()
                user_pass += ":*" + base64.b64encode(pass_bytes).decode()[:4]

        if user_pass:
            user_pass = "******" % user_pass

        uri = host_port + user_pass

        if self.database:
            if uri:
                uri += "/"
            uri += self.database

        return "[%s]://%s" % (self.type, uri)

    def __repr__(self) -> str:
        """Display the information in text mode."""
        if self.project_password:
            # 4 chars in base-64 is 3 bytes. 256**3 should be enough to know if you have the wrong
            # password.
            pass_bytes: bytes = hashlib.sha256(
                self.project_password.encode()).digest()
            passwd = "-" + base64.b64encode(pass_bytes).decode()[:4]
        else:
            passwd = ""
        return "<ProjectConfig%s name=%r uri=%r>" % (
            passwd,
            self.description,
            self.get_uri(show_password=False),
        )

    def __eq__(self, other: Any) -> bool:
        """Test for equality."""
        if not isinstance(other, ProjectConfig):
            return False
        if other.type != self.type:
            return False
        if other.get_uri(show_password=True) != self.get_uri(
                show_password=True):
            return False
        if other.description != self.description:
            return False
        if other.project_password != self.project_password:
            return False
        return True

    def load_projectxml(self) -> bool:
        """Collect the connection information from an xml file."""

        file_name = self.filename
        if not os.path.isfile(file_name):
            raise ValueError("El proyecto %r no existe." % file_name)

        tree = ET.parse(file_name)
        root = tree.getroot()
        version = VersionNumber(root.get("Version"), default="1.0")
        self.version = version
        self.description = ""
        for xmldescription in root.findall("name"):
            self.description = xmldescription.text or ""
        profile_pwd = ""
        for profile in root.findall("profile-data"):
            profile_pwd = getattr(profile.find("password"), "text", "")
            if profile_pwd:
                break

        self.password_required = True
        self.checkProfilePasswordForVersion(self.project_password, profile_pwd,
                                            version)

        if self.project_password and self.version > VERSION_1_1:
            key_salt = hashlib.sha256(profile_pwd.encode()).digest()
            key = hashlib.pbkdf2_hmac("sha256", self.project_password.encode(),
                                      key_salt, 10000)
            key64 = base64.urlsafe_b64encode(key)
            self.fernet = Fernet(key64)
        else:
            self.fernet = None

        from pineboolib.application.database.pnsqldrivers import PNSqlDrivers

        sql_drivers_manager = PNSqlDrivers()
        self.database = self.retrieveCipherSubElement(root, "database-name")
        for db in root.findall("database-server"):
            self.host = self.retrieveCipherSubElement(db, "host")
            port_text = self.retrieveCipherSubElement(db, "port")
            self.port = int(port_text) if port_text else None
            self.type = self.retrieveCipherSubElement(db, "type")

            # FIXME: Move this to project, or to the connection handler.
            if self.type not in sql_drivers_manager.aliasList():
                LOGGER.warning(
                    "Esta versión de pineboo no soporta el driver '%s'" %
                    self.type)

        for credentials in root.findall("database-credentials"):
            self.username = self.retrieveCipherSubElement(
                credentials, "username")
            self.password = self.retrieveCipherSubElement(
                credentials, "password")
            if self.password and self.fernet is None:
                self.password = base64.b64decode(self.password).decode()
        self.password_required = False

        return True

    @classmethod
    def encodeProfilePasswordForVersion(cls, password: str,
                                        save_version: VersionNumber) -> str:
        """
        Hash a password for a profile/projectconfig using the protocol for specified version.
        """
        if password == "":
            return ""
        if save_version < VERSION_1_1:
            return password

        if save_version < VERSION_1_2:
            return hashlib.sha256(password.encode()).hexdigest()
        # Minimum salt size recommended is 8 bytes
        # multiple of 3 bytes as it is shorter in base64
        salt = os.urandom(9)
        hmac = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, 10000)
        dict_passwd = {
            # Algorithm:
            # .. pbkdf2: short algorithm name
            # .. sha256: hash function used
            # .. 4: number of zeroes used on iterations
            "algorithm": "pbkdf2-sha256-4",
            "salt": base64.b64encode(salt).decode(),
            "hash": base64.b64encode(hmac).decode(),
        }
        hashed_password = "******" % dict_passwd

        return hashed_password

    @classmethod
    def checkProfilePasswordForVersion(cls, user_pwd: str, profile_pwd: str,
                                       version: VersionNumber) -> None:
        """
        Check a saved password against a user-supplied one.

        user_pwd: User-supplied password in clear text.
        profile_pwd: Raw data saved as password in projectconfig file.
        version: Version number used for checks.

        This function returns None and raises PasswordMismatchError if the password is wrong.
        We can only check if it is good. It's not a good idea to check if two encoded passwords
        are the same, because most secure methods will store different encoded versions every
        time we try to encode again.
        """
        if not profile_pwd:
            return

        if version < VERSION_1_1:
            if user_pwd == profile_pwd:
                return
            raise PasswordMismatchError("La contraseña es errónea")

        if version < VERSION_1_2:
            user_hash = hashlib.sha256(user_pwd.encode()).hexdigest()
            if profile_pwd == user_hash:
                return
            raise PasswordMismatchError("La contraseña es errónea")

        algo, *algo_extra = profile_pwd.split(":")
        if algo != "pbkdf2-sha256-4":
            raise Exception("Unsupported password algorithm %r" % algo)

        salt64, hash64 = algo_extra

        salt = base64.b64decode(salt64.encode())

        user_hash2 = hashlib.pbkdf2_hmac("sha256", user_pwd.encode(), salt,
                                         10000)
        user_hash64 = base64.b64encode(user_hash2).decode()
        if user_hash64 == hash64:
            return

        raise PasswordMismatchError("La contraseña es errónea")

    def createCipherSubElement(self, parent: ET.Element, tagname: str,
                               text: str) -> ET.Element:
        """Create a XML SubElement ciphered if self.fernet is present."""
        child = ET.SubElement(parent, tagname)
        if self.fernet is None:
            child.text = text
            return child
        # NOTE: This method returns ciphertext even for empty strings! This is intended.
        # ... this is to avoid anyone knowing if a field is empty or not.
        if len(text) < 64:
            # Right Pad with new line at least up to 64 bytes. Avoid giving out field size.
            text = text.ljust(64, "\n")
        encoded_bytes = self.fernet.encrypt(text.encode())
        encoded_text = base64.b64encode(encoded_bytes).decode()
        child.set("cipher-method", "cryptography.Fernet")
        child.set("cipher-text", encoded_text)
        return child

    def retrieveCipherSubElement(self, parent: ET.Element,
                                 tagname: str) -> str:
        """Get a XML SubElement ciphered if self.fernet is present."""
        child = parent.find(tagname)
        if child is None:
            raise ValueError("Tag %r not present" % tagname)

        cipher_method = child.get("cipher-method")
        if cipher_method is None:
            return child.text or ""
        if self.fernet is None:
            raise Exception(
                "Tried to load ciphered tag %r with no loaded cipher" %
                tagname)
        cipher_text = child.get("cipher-text")
        if cipher_method != "cryptography.Fernet":
            raise ValueError("Cipher method %r not supported." % cipher_method)

        if not cipher_text:
            raise ValueError("Missing ciphertext for %r" % tagname)

        cipher_bytes = base64.b64decode(cipher_text.encode())
        text = self.fernet.decrypt(cipher_bytes).decode()
        text = text.rstrip("\n")
        return text

    def save_projectxml(self, overwrite_existing: bool = True) -> None:
        """
        Save the connection.
        """
        profile = ET.Element("Profile")
        profile.set("Version", str(self.SAVE_VERSION))
        description = self.description
        filename = self.filename
        if not os.path.exists(self.profile_dir):
            os.mkdir(self.profile_dir)

        if not overwrite_existing and os.path.exists(filename):
            raise ProfileAlreadyExistsError

        passwDB = self.password or ""

        profile_user = ET.SubElement(profile, "profile-data")
        profile_password = ET.SubElement(profile_user, "password")
        profile_password.text = self.encodeProfilePasswordForVersion(
            self.project_password, self.SAVE_VERSION)
        if self.project_password and self.SAVE_VERSION > VERSION_1_1:
            key_salt = hashlib.sha256(profile_password.text.encode()).digest()
            key = hashlib.pbkdf2_hmac("sha256", self.project_password.encode(),
                                      key_salt, 10000)
            key64 = base64.urlsafe_b64encode(key)
            self.fernet = Fernet(key64)
        else:
            # Mask the password if no cipher is used!
            passwDB = base64.b64encode(passwDB.encode()).decode()
            self.fernet = None
        name = ET.SubElement(profile, "name")
        name.text = description
        dbs = ET.SubElement(profile, "database-server")
        self.createCipherSubElement(dbs, "type", text=self.type)
        self.createCipherSubElement(dbs, "host", text=self.host or "")
        self.createCipherSubElement(dbs,
                                    "port",
                                    text=str(self.port) if self.port else "")

        dbc = ET.SubElement(profile, "database-credentials")
        self.createCipherSubElement(dbc, "username", text=self.username or "")
        self.createCipherSubElement(dbc, "password", text=passwDB)

        self.createCipherSubElement(profile,
                                    "database-name",
                                    text=self.database)

        pretty_print_xml(profile)

        tree = ET.ElementTree(profile)

        tree.write(filename, xml_declaration=True, encoding="utf-8")
        self.version = self.SAVE_VERSION

    @classmethod
    def translate_connstring(
            cls, connstring: str) -> Tuple[str, str, str, str, int, str]:
        """
        Translate a DSN connection string into user, pass, etc.

        Accept a "connstring" parameter that has the form user @ host / dbname
        and returns all parameters separately. It takes into account the
        default values ​​and the different abbreviations that exist.
        """
        user = "******"
        passwd = ""
        host = "127.0.0.1"
        port = "5432"
        driver_alias = "PostgreSQL (PSYCOPG2)"
        user_pass = None
        host_port = None
        if "/" not in connstring:
            dbname = connstring
            if not re.match(r"\w+", dbname):
                raise ValueError("base de datos no valida")
            return user, passwd, driver_alias, host, int(port), dbname

        uphpstring = connstring[:connstring.rindex("/")]
        dbname = connstring[connstring.rindex("/") + 1:]
        up, hp = uphpstring.split("@")
        conn_list = [None, None, up, hp]
        _user_pass, _host_port = conn_list[-2], conn_list[-1]

        if _user_pass:
            user_pass = _user_pass.split(":") + ["", "", ""]
            user, passwd, driver_alias = (
                user_pass[0],
                user_pass[1] or passwd,
                user_pass[2] or driver_alias,
            )
            if user_pass[3]:
                raise ValueError(
                    "La cadena de usuario debe tener el formato user:pass:driver."
                )

        if _host_port:
            host_port = _host_port.split(":") + [""]
            host, port = host_port[0], host_port[1] or port
            if host_port[2]:
                raise ValueError("La cadena de host debe ser host:port.")

        if not re.match(r"\w+", user):
            raise ValueError("Usuario no valido")
        if not re.match(r"\w+", dbname):
            raise ValueError("base de datos no valida")
        if not re.match(r"\d+", port):
            raise ValueError("puerto no valido")
        LOGGER.debug(
            "user:%s, passwd:%s, driver_alias:%s, host:%s, port:%s, dbname:%s",
            user,
            "*" * len(passwd),
            driver_alias,
            host,
            port,
            dbname,
        )
        return user, passwd, driver_alias, host, int(port), dbname
Exemple #13
0
        global fenetre_actu
        fenetre_actu.pack_forget()
        self.pack(fill=BOTH)
        fenetre_actu = self


try:
    file_key = open('key.key', 'rb')
    key = file_key.read()
    file_key.close()
    file_password = open('password.txt', 'rb')
    password_encrypted = file_password.read()
    file_password.close()
    assert password_encrypted != ""
    f = Fernet(key)
    password = f.decrypt(password_encrypted)
    password = password.decode()
except:
    key = Fernet.generate_key()
    f = Fernet(key)
    password = input('Quel est le mot de passe')
    password_encrypted = password.encode()
    password_encrypted = f.encrypt(password_encrypted)
    file_key = open('key.key', 'wb')
    file_key.write(key)
    file_key.close()
    file_password = open('password.txt', 'wb')
    file_password.write(password_encrypted)
    file_password.close()

web = ChromeMbn('f.henrotterobe', password)
Exemple #14
0
# we will be encryting the below string.

message = str(input(" Write Here your message \n"))

# generate a key for encryptio and decryption
# You can use fernet to generate
# the key or use random key generator
# here I'm using fernet to generate key

key = Fernet.generate_key()

# Instance the Fernet class with the key

fernet = Fernet(key)

# then use the Fernet class instance
# to encrypt the string string must must
# be encoded to byte string before encryption
encMessage = fernet.encrypt(message.encode())

print("original string: ", message)
print("encrypted string: ", encMessage)

# decrypt the encrypted string with the
# Fernet instance of the key,
# that was used for encrypting the string
# encoded byte string is returned by decrypt method,
# so decode it to string with decode methos
decMessage = fernet.decrypt(encMessage).decode()

print("decrypted string: ", decMessage)