Python cryptography.hazmat.primitives.serialization.load_pem_private_key() Examples

The following are 30 code examples of cryptography.hazmat.primitives.serialization.load_pem_private_key(). 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 cryptography.hazmat.primitives.serialization , or try the search function .
Example #1
Source File: key_utils.py    From aws-ec2-instance-connect-cli with Apache License 2.0 7 votes vote down vote up
def convert_pem_to_der(pem_key):
    """
    Converts a given key from PEM to DER format.

    :param pem_key: PEM-encoded key bytes
    :type pem_key: bytearray
    :return: DER-encoded key bytes
    :rtype: bytearray
    """
    first_line = pem_key.decode().split('\n', 1)[0]
    is_private = first_line == begin_key.format(private_str)
    if is_private:
        loaded_key = crypto_serialization.load_pem_private_key(pem_key, backend=crypto_default_backend())
        return serialize_key(loaded_key, encoding='DER', return_private=is_private)
    else:
        loaded_key = crypto_serialization.load_pem_public_key(pem_key, backend=crypto_default_backend())
        return loaded_key.public_bytes(encoding=crypto_serialization.Encoding.DER,
                                       format=crypto_serialization.PublicFormat.SubjectPublicKeyInfo) 
Example #2
Source File: minion_config.py    From python-tripleoclient with Apache License 2.0 6 votes vote down vote up
def _get_public_tls_parameters(service_certificate_path):
    with open(service_certificate_path, "rb") as pem_file:
        pem_data = pem_file.read()
        cert = x509.load_pem_x509_certificate(pem_data, default_backend())
        private_key = serialization.load_pem_private_key(
            pem_data,
            password=None,
            backend=default_backend())

        key_pem = private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption())
        cert_pem = cert.public_bytes(serialization.Encoding.PEM)
        return {
            'SSLCertificate': cert_pem,
            'SSLKey': key_pem
        } 
Example #3
Source File: wrapping_keys.py    From aws-encryption-sdk-python with Apache License 2.0 6 votes vote down vote up
def __init__(self, wrapping_algorithm, wrapping_key, wrapping_key_type, password=None):
        """Prepares initial values."""
        self.wrapping_algorithm = wrapping_algorithm
        self.wrapping_key_type = wrapping_key_type
        if wrapping_key_type is EncryptionKeyType.PRIVATE:
            self._wrapping_key = serialization.load_pem_private_key(
                data=wrapping_key, password=password, backend=default_backend()
            )
        elif wrapping_key_type is EncryptionKeyType.PUBLIC:
            self._wrapping_key = serialization.load_pem_public_key(data=wrapping_key, backend=default_backend())
        elif wrapping_key_type is EncryptionKeyType.SYMMETRIC:
            self._wrapping_key = wrapping_key
            self._derived_wrapping_key = derive_data_encryption_key(
                source_key=self._wrapping_key, algorithm=self.wrapping_algorithm.algorithm, message_id=None
            )
        else:
            raise InvalidDataKeyError("Invalid wrapping_key_type: {}".format(wrapping_key_type)) 
Example #4
Source File: test_local.py    From octavia with Apache License 2.0 6 votes vote down vote up
def test_generate_cert_key_pair(self):
        cn = 'testCN'
        bit_length = 512

        # Attempt to generate a cert/key pair
        cert_object = self.cert_generator.generate_cert_key_pair(
            cn=cn,
            validity=2 * 365 * 24 * 60 * 60,
            bit_length=bit_length,
            passphrase=self.ca_private_key_passphrase,
            ca_cert=self.ca_certificate,
            ca_key=self.ca_private_key,
            ca_key_pass=self.ca_private_key_passphrase
        )

        # Validate that the cert and key are loadable
        cert = x509.load_pem_x509_certificate(
            data=cert_object.certificate, backend=backends.default_backend())
        self.assertIsNotNone(cert)

        key = serialization.load_pem_private_key(
            data=cert_object.private_key,
            password=cert_object.private_key_passphrase,
            backend=backends.default_backend())
        self.assertIsNotNone(key) 
Example #5
Source File: cloudfront_utils.py    From marsha with MIT License 6 votes vote down vote up
def rsa_signer(message):
    """Sign a message with an rsa key pair found on the file system for CloudFront signed urls.

    Parameters
    ----------
    message : Type[string]
        the message for which we want to compute a signature

    Returns
    -------
    string
        The rsa signature

    """
    try:
        with open(settings.CLOUDFRONT_PRIVATE_KEY_PATH, "rb") as key_file:
            private_key = serialization.load_pem_private_key(
                key_file.read(), password=None, backend=default_backend()
            )
    except FileNotFoundError:
        raise MissingRSAKey()

    # The following line is excluded from bandit security check because cloudfront supports
    # only sha1 hash for signed URLs.
    return private_key.sign(message, padding.PKCS1v15(), hashes.SHA1())  # nosec 
Example #6
Source File: cert_parser.py    From octavia with Apache License 2.0 6 votes vote down vote up
def _read_private_key(private_key_pem, passphrase=None):
    """Reads a private key PEM block and returns a RSAPrivatekey

    :param private_key_pem: The private key PEM block
    :param passphrase: Optional passphrase needed to decrypt the private key
    :returns: a RSAPrivatekey object
    """
    if passphrase and isinstance(passphrase, str):
        passphrase = passphrase.encode("utf-8")
    if isinstance(private_key_pem, str):
        private_key_pem = private_key_pem.encode('utf-8')

    try:
        return serialization.load_pem_private_key(private_key_pem, passphrase,
                                                  backends.default_backend())
    except Exception:
        LOG.exception("Passphrase required.")
        raise exceptions.NeedsPassphrase 
Example #7
Source File: certs.py    From dcos-deploy with Apache License 2.0 6 votes vote down vote up
def _convert_key(encoding_name, format_name, private_key):
    if not encoding_name and not format_name:
        return private_key
    backend = backends.default_backend()
    key_obj = serialization.load_pem_private_key(private_key.encode("utf-8"), None, backend)
    if encoding_name.lower() == "pem":
        encoding = serialization.Encoding.PEM
    elif encoding_name.lower() == "der":
        encoding = serialization.Encoding.DER
    else:
        raise Exception("Unknown key encoding: %s" % encoding_name)
    if format_name.lower() == "pkcs1":
        format = serialization.PrivateFormat.TraditionalOpenSSL
    elif format_name.lower() == "pkcs8":
        format = serialization.PrivateFormat.PKCS8
    else:
        raise Exception("Unknown key format: %s" % format_name)

    target_key = key_obj.private_bytes(encoding=encoding, format=format, encryption_algorithm=serialization.NoEncryption())
    return target_key.decode("utf-8") 
Example #8
Source File: cfn_rsakey_provider.py    From cfn-secret-provider with Apache License 2.0 6 votes vote down vote up
def get_key(self):
        response = self.ssm.get_parameter(
            Name=self.name_from_physical_resource_id(), WithDecryption=True
        )
        private_key = response["Parameter"]["Value"].encode("ascii")

        key = crypto_serialization.load_pem_private_key(
            private_key, password=None, backend=crypto_default_backend()
        )

        private_key = key.private_bytes(
            crypto_serialization.Encoding.PEM,
            self.key_format,
            crypto_serialization.NoEncryption(),
        )

        public_key = key.public_key().public_bytes(
            crypto_serialization.Encoding.OpenSSH,
            crypto_serialization.PublicFormat.OpenSSH,
        )
        return private_key.decode("ascii"), public_key.decode("ascii") 
Example #9
Source File: es256.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
def from_string(cls, key, key_id=None):
        """Construct a RSASigner from a private key in PEM format.

        Args:
            key (Union[bytes, str]): Private key in PEM format.
            key_id (str): An optional key id used to identify the private key.

        Returns:
            google.auth.crypt._cryptography_rsa.RSASigner: The
            constructed signer.

        Raises:
            ValueError: If ``key`` is not ``bytes`` or ``str`` (unicode).
            UnicodeDecodeError: If ``key`` is ``bytes`` but cannot be decoded
                into a UTF-8 ``str``.
            ValueError: If ``cryptography`` "Could not deserialize key data."
        """
        key = _helpers.to_bytes(key)
        private_key = serialization.load_pem_private_key(
            key, password=None, backend=_BACKEND
        )
        return cls(private_key, key_id=key_id) 
Example #10
Source File: _cryptography_rsa.py    From google-auth-library-python with Apache License 2.0 6 votes vote down vote up
def from_string(cls, key, key_id=None):
        """Construct a RSASigner from a private key in PEM format.

        Args:
            key (Union[bytes, str]): Private key in PEM format.
            key_id (str): An optional key id used to identify the private key.

        Returns:
            google.auth.crypt._cryptography_rsa.RSASigner: The
            constructed signer.

        Raises:
            ValueError: If ``key`` is not ``bytes`` or ``str`` (unicode).
            UnicodeDecodeError: If ``key`` is ``bytes`` but cannot be decoded
                into a UTF-8 ``str``.
            ValueError: If ``cryptography`` "Could not deserialize key data."
        """
        key = _helpers.to_bytes(key)
        private_key = serialization.load_pem_private_key(
            key, password=None, backend=_BACKEND
        )
        return cls(private_key, key_id=key_id) 
Example #11
Source File: signer.py    From asap-authentication-python with MIT License 6 votes vote down vote up
def _obtain_private_key(self, key_identifier, private_key_pem):
        """ returns a loaded instance of the given private key either from
            cache or from the given private_key_pem.
        """
        priv_key = self._private_keys_cache.get(key_identifier.key_id, None)
        if priv_key is not None:
            return priv_key
        if not isinstance(private_key_pem, bytes):
            private_key_pem = private_key_pem.encode()
        priv_key = serialization.load_pem_private_key(
            private_key_pem,
            password=None,
            backend=default_backend()
        )
        if len(self._private_keys_cache) > 10:
            self._private_keys_cache = dict()
        self._private_keys_cache[key_identifier.key_id] = priv_key
        return priv_key 
Example #12
Source File: endpoint.py    From txacme with MIT License 6 votes vote down vote up
def load_or_create_client_key(pem_path):
    """
    Load the client key from a directory, creating it if it does not exist.

    .. note:: The client key that will be created will be a 2048-bit RSA key.

    :type pem_path: ``twisted.python.filepath.FilePath``
    :param pem_path: The certificate directory
        to use, as with the endpoint.
    """
    acme_key_file = pem_path.asTextMode().child(u'client.key')
    if acme_key_file.exists():
        key = serialization.load_pem_private_key(
            acme_key_file.getContent(),
            password=None,
            backend=default_backend())
    else:
        key = generate_private_key(u'rsa')
        acme_key_file.setContent(
            key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=serialization.NoEncryption()))
    return JWKRSA(key=key) 
Example #13
Source File: engine.py    From appkernel with Apache License 2.0 6 votes vote down vote up
def __init_crypto(self):
        # https://stackoverflow.com/questions/29650495/how-to-verify-a-jwt-using-python-pyjwt-with-public-key
        with self.app.app_context():
            with open('{}/keys/appkernel.pem'.format(self.cfg_dir), "rb") as key_file:
                private_key = serialization.load_pem_private_key(
                    key_file.read(),
                    password=None,
                    backend=default_backend()
                )
                config.private_key = private_key
            with open('{}/keys/appkernel.pub'.format(self.cfg_dir), 'rb') as key_file:
                public_key = serialization.load_pem_public_key(
                    key_file.read(),
                    backend=default_backend()
                )
                config.public_key = public_key 
Example #14
Source File: Trust.py    From Uranium with GNU Lesser General Public License v3.0 6 votes vote down vote up
def loadPrivateKey(private_filename: str, optional_password: Optional[str]) -> Optional[RSAPrivateKey]:
        """Load a private key from a file.

        :param private_filename: The filename of the file containing the private key.
        :param optional_password: The key can be signed with a password as well (or not).
        :return: The private key contained in the file.
        """

        try:
            password_bytes = None if optional_password is None else optional_password.encode()
            with open(private_filename, "rb") as file:
                private_key = load_pem_private_key(file.read(), backend=default_backend(), password=password_bytes)
                return private_key
        except:  # Yes, we  do really want this on _every_ exception that might occur.
            Logger.logException("e", "Couldn't load private-key.")
        return None 
Example #15
Source File: undercloud_config.py    From python-tripleoclient with Apache License 2.0 6 votes vote down vote up
def _get_public_tls_parameters(service_certificate_path):
    with open(service_certificate_path, "rb") as pem_file:
        pem_data = pem_file.read()
        cert = x509.load_pem_x509_certificate(pem_data, default_backend())
        private_key = serialization.load_pem_private_key(
            pem_data,
            password=None,
            backend=default_backend())

        key_pem = private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption())
        cert_pem = cert.public_bytes(serialization.Encoding.PEM)
        return {
            'SSLCertificate': cert_pem,
            'SSLKey': key_pem
        } 
Example #16
Source File: tests_command_regenerate_ocsp_keys.py    From django-ca with GNU General Public License v3.0 6 votes vote down vote up
def assertKey(self, ca, key_type=RSAPrivateKey, password=None):
        priv_path = 'ocsp/%s.key' % ca.serial
        cert_path = 'ocsp/%s.pem' % ca.serial

        self.assertTrue(ca_storage.exists(priv_path))
        self.assertTrue(ca_storage.exists(cert_path))

        with ca_storage.open(priv_path, 'rb') as stream:
            priv = stream.read()
        priv = load_pem_private_key(priv, password, default_backend())
        self.assertIsInstance(priv, key_type)

        with ca_storage.open(cert_path, 'rb') as stream:
            cert = stream.read()
        cert = x509.load_pem_x509_certificate(cert, default_backend())
        self.assertIsInstance(cert, x509.Certificate)

        db_cert = Certificate.objects.exclude(pk__in=self.existing_certs).first()
        self.assertEqual(db_cert.authority_information_access.ocsp, [])

        return priv, cert 
Example #17
Source File: user.py    From fabric-sdk-py with Apache License 2.0 6 votes vote down vote up
def _restore_state(self):
        """Restore user state."""
        try:
            state = self._state_store.get_value(self._state_store_key)
            state_dict = pickle.loads(
                binascii.unhexlify(state.encode("utf-8")))
            self._name = state_dict['name']
            self.enrollment_secret = state_dict['enrollment_secret']
            enrollment = state_dict['enrollment']
            if enrollment:
                private_key = serialization.load_pem_private_key(
                    enrollment['private_key'],
                    password=None,
                    backend=default_backend()
                )
                cert = enrollment['cert']
                self.enrollment = Enrollment(private_key, cert)
            self.affiliation = state_dict['affiliation']
            self.account = state_dict['account']
            self.roles = state_dict['roles']
            self._org = state_dict['org']
            self.msp_id = state_dict['msp_id']
        except Exception as e:
            raise IOError("Cannot deserialize the user", e) 
Example #18
Source File: _cryptography_rsa.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def from_string(cls, key, key_id=None):
        """Construct a RSASigner from a private key in PEM format.

        Args:
            key (Union[bytes, str]): Private key in PEM format.
            key_id (str): An optional key id used to identify the private key.

        Returns:
            google.auth.crypt._cryptography_rsa.RSASigner: The
            constructed signer.

        Raises:
            ValueError: If ``key`` is not ``bytes`` or ``str`` (unicode).
            UnicodeDecodeError: If ``key`` is ``bytes`` but cannot be decoded
                into a UTF-8 ``str``.
            ValueError: If ``cryptography`` "Could not deserialize key data."
        """
        key = _helpers.to_bytes(key)
        private_key = serialization.load_pem_private_key(
            key, password=None, backend=_BACKEND)
        return cls(private_key, key_id=key_id) 
Example #19
Source File: _cryptography_rsa.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def from_string(cls, key, key_id=None):
        """Construct a RSASigner from a private key in PEM format.

        Args:
            key (Union[bytes, str]): Private key in PEM format.
            key_id (str): An optional key id used to identify the private key.

        Returns:
            google.auth.crypt._cryptography_rsa.RSASigner: The
            constructed signer.

        Raises:
            ValueError: If ``key`` is not ``bytes`` or ``str`` (unicode).
            UnicodeDecodeError: If ``key`` is ``bytes`` but cannot be decoded
                into a UTF-8 ``str``.
            ValueError: If ``cryptography`` "Could not deserialize key data."
        """
        key = _helpers.to_bytes(key)
        private_key = serialization.load_pem_private_key(
            key, password=None, backend=_BACKEND)
        return cls(private_key, key_id=key_id) 
Example #20
Source File: _cryptography_rsa.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def from_string(cls, key, key_id=None):
        """Construct a RSASigner from a private key in PEM format.

        Args:
            key (Union[bytes, str]): Private key in PEM format.
            key_id (str): An optional key id used to identify the private key.

        Returns:
            google.auth.crypt._cryptography_rsa.RSASigner: The
            constructed signer.

        Raises:
            ValueError: If ``key`` is not ``bytes`` or ``str`` (unicode).
            UnicodeDecodeError: If ``key`` is ``bytes`` but cannot be decoded
                into a UTF-8 ``str``.
            ValueError: If ``cryptography`` "Could not deserialize key data."
        """
        key = _helpers.to_bytes(key)
        private_key = serialization.load_pem_private_key(
            key, password=None, backend=_BACKEND)
        return cls(private_key, key_id=key_id) 
Example #21
Source File: _cryptography_rsa.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def from_string(cls, key, key_id=None):
        """Construct a RSASigner from a private key in PEM format.

        Args:
            key (Union[bytes, str]): Private key in PEM format.
            key_id (str): An optional key id used to identify the private key.

        Returns:
            google.auth.crypt._cryptography_rsa.RSASigner: The
            constructed signer.

        Raises:
            ValueError: If ``key`` is not ``bytes`` or ``str`` (unicode).
            UnicodeDecodeError: If ``key`` is ``bytes`` but cannot be decoded
                into a UTF-8 ``str``.
            ValueError: If ``cryptography`` "Could not deserialize key data."
        """
        key = _helpers.to_bytes(key)
        private_key = serialization.load_pem_private_key(
            key, password=None, backend=_BACKEND)
        return cls(private_key, key_id=key_id) 
Example #22
Source File: _cryptography_rsa.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def from_string(cls, key, key_id=None):
        """Construct a RSASigner from a private key in PEM format.

        Args:
            key (Union[bytes, str]): Private key in PEM format.
            key_id (str): An optional key id used to identify the private key.

        Returns:
            google.auth.crypt._cryptography_rsa.RSASigner: The
            constructed signer.

        Raises:
            ValueError: If ``key`` is not ``bytes`` or ``str`` (unicode).
            UnicodeDecodeError: If ``key`` is ``bytes`` but cannot be decoded
                into a UTF-8 ``str``.
            ValueError: If ``cryptography`` "Could not deserialize key data."
        """
        key = _helpers.to_bytes(key)
        private_key = serialization.load_pem_private_key(
            key, password=None, backend=_BACKEND)
        return cls(private_key, key_id=key_id) 
Example #23
Source File: _cryptography_rsa.py    From alfred-gmail with MIT License 6 votes vote down vote up
def from_string(cls, key, key_id=None):
        """Construct a RSASigner from a private key in PEM format.

        Args:
            key (Union[bytes, str]): Private key in PEM format.
            key_id (str): An optional key id used to identify the private key.

        Returns:
            google.auth.crypt._cryptography_rsa.RSASigner: The
            constructed signer.

        Raises:
            ValueError: If ``key`` is not ``bytes`` or ``str`` (unicode).
            UnicodeDecodeError: If ``key`` is ``bytes`` but cannot be decoded
                into a UTF-8 ``str``.
            ValueError: If ``cryptography`` "Could not deserialize key data."
        """
        key = _helpers.to_bytes(key)
        private_key = serialization.load_pem_private_key(
            key, password=None, backend=_BACKEND)
        return cls(private_key, key_id=key_id) 
Example #24
Source File: utils.py    From wechatpy with MIT License 6 votes vote down vote up
def rsa_decrypt(encrypted_data, pem, password=None):
    """
    rsa 解密
    :param encrypted_data: 待解密 bytes
    :param pem: RSA private key 内容/binary
    :param password: RSA private key pass phrase
    :return: 解密后的 binary
    """
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.asymmetric import padding

    encrypted_data = to_binary(encrypted_data)
    pem = to_binary(pem)
    private_key = serialization.load_pem_private_key(pem, password, backend=default_backend())
    data = private_key.decrypt(
        encrypted_data, padding=padding.OAEP(mgf=padding.MGF1(hashes.SHA1()), algorithm=hashes.SHA1(), label=None,),
    )
    return data 
Example #25
Source File: test_preauth.py    From integration with Apache License 2.0 5 votes vote down vote up
def get_pub_key(device):
        """Extract the device's public key from its private key."""

        Client.__wait_for_keygen(device)
        keystr = device.run("cat {}".format(Client.PRIV_KEY))
        private_key = serialization.load_pem_private_key(
            data=keystr.encode() if isinstance(keystr, str) else keystr,
            password=None,
            backend=default_backend(),
        )
        public_key = private_key.public_key()
        return public_key.public_bytes(
            serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo
        ).decode() 
Example #26
Source File: gdata.py    From lrrbot with Apache License 2.0 5 votes vote down vote up
def get_oauth_token(scopes):
	with open("keys.json") as f:
		keys = json.load(f)
	t = int(time.time())

	header = json.dumps({"alg":"RS256", "typ":"JWT"}).encode("utf-8")
	claim = json.dumps({
		"iss": keys["client_email"],
		"scope": " ".join(scopes),
		"aud": "https://accounts.google.com/o/oauth2/token",
		"iat": t,
		"exp": t+60*60,
	}).encode("utf-8")

	data = base64_encode(header) + b'.' + base64_encode(claim)

	key = load_pem_private_key(keys["private_key"].encode("utf-8"), None, openssl.backend)
	signature = key.sign(data, PKCS1v15(), SHA256())

	jwt = (data + b'.' + base64_encode(signature)).decode("utf-8")

	data = {"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", "assertion": jwt}

	ret = json.loads((await common.http.request_coro("https://oauth2.googleapis.com/token", data, "POST")))
	if "error" in ret:
		raise Exception(ret["error"])
	return ret 
Example #27
Source File: __init__.py    From asymmetric-jwt-auth with ISC License 5 votes vote down vote up
def decrypt_key(key, password):
    """
    Decrypt an encrypted private key.

    :param key: Encrypted private key as a string.
    :param password: Key pass-phrase.
    :return: Decrypted private key as a string.
    """
    private = serialization.load_pem_private_key(key, password=password, backend=default_backend())
    return private.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()) 
Example #28
Source File: snowflake.py    From fireant with Apache License 2.0 5 votes vote down vote up
def _load_private_key_data(self):
        if self.private_key_data is None:
            return None

        private_key_password = None \
            if self.private_key_password is None \
            else self.private_key_password.encode()

        pkey = serialization.load_pem_private_key(self.private_key_data.encode(),
                                                  private_key_password,
                                                  backend=default_backend())

        return pkey.private_bytes(encoding=serialization.Encoding.DER,
                                  format=serialization.PrivateFormat.PKCS8,
                                  encryption_algorithm=serialization.NoEncryption()) 
Example #29
Source File: crypto.py    From integration with Apache License 2.0 5 votes vote down vote up
def rsa_sign_data(data, private_key):
    _private_key = serialization.load_pem_private_key(
        private_key if isinstance(private_key, bytes) else private_key.encode(),
        password=None,
        backend=default_backend(),
    )
    signature = _private_key.sign(
        data if isinstance(data, bytes) else data.encode(),
        padding.PKCS1v15(),
        hashes.SHA256(),
    )
    return b64encode(signature).decode() 
Example #30
Source File: FileCrypter.py    From SupergirlOnCrypt with Do What The F*ck You Want To Public License 5 votes vote down vote up
def decrypt_file(self, file_name, privateKeyStr):
        if not os.path.isfile(file_name):
            return


        private_key = serialization.load_pem_private_key(
            bytes(privateKeyStr, 'utf-8'),
            password=None,
            backend=default_backend()
        )

        tmp_name = file_name[:-10]
        aes_line = open(tmp_name + '.kryptonian', 'rb').readline().strip()
        aes_line = base64.b64decode(aes_line)

        aes_iv_clear = private_key.decrypt(
            aes_line,
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA256()),
                algorithm=hashes.SHA1(),
                label=None
            )
        )
        aes_iv_clear = aes_iv_clear.decode(self.encoding)
        aes_iv_clear = aes_iv_clear.split(';')[0]
        aes_iv_clear = base64.b64decode(aes_iv_clear)

        with open(file_name, 'rb') as fo:
            ciphertext = fo.read()
        dec = self.decrypt(ciphertext, aes_iv_clear)
        with open(file_name[:-10], 'wb') as fo:
            fo.write(dec)
        os.remove(file_name)
        os.remove(tmp_name + '.kryptonian')