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

The following are 22 code examples of cryptography.hazmat.primitives.serialization.load_der_public_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 6 votes vote down vote up
def convert_der_to_pem(der_key, is_private=False):
    """
    Converts a given key from DER to PEM format.

    :param der_key: DER-encoded key bytes
    :type der_key: bytearray
    :param is_private: Whether the key is public or private. Default: False
    :type is_private: bool
    :return: PEM-encoded key bytes
    :rtype: bytearray
    """
    if is_private:
        loaded_key = crypto_serialization.load_der_private_key(der_key, backend=crypto_default_backend())
        return serialize_key(loaded_key, encoding='PEM', return_private=is_private)
    else:
        loaded_key = crypto_serialization.load_der_public_key(der_key, backend=crypto_default_backend())
        return loaded_key.public_bytes(encoding=crypto_serialization.Encoding.PEM,
                                       format=crypto_serialization.PublicFormat.SubjectPublicKeyInfo) 
Example #2
Source File: app_config.py    From dash-masternode-tool with MIT License 6 votes vote down vote up
def set_rpc_encryption_pubkey(self, key: str):
        """
        AES public key for additional RPC encryption, dedicated for calls transmitting sensitive information
        like protx. Accepted formats: PEM, DER.
        """
        try:
            if key:
                # validate public key by deserializing it
                if re.fullmatch(r'^([0-9a-fA-F]{2})+$', key):
                    serialization.load_der_public_key(bytes.fromhex(key), backend=default_backend())
                else:
                    pubkey = serialization.load_pem_public_key(key.encode('ascii'), backend=default_backend())
                    raw = pubkey.public_bytes(serialization.Encoding.DER,
                                              format=serialization.PublicFormat.SubjectPublicKeyInfo)
                    key = raw.hex()

            if self.__rpc_encryption_pubkey_object and (self.__rpc_encryption_pubkey_der != key or not key):
                self.__rpc_encryption_pubkey_der = None

            self.__rpc_encryption_pubkey_der = key
        except Exception as e:
            logging.exception('Exception occurred')
            raise 
Example #3
Source File: cse.py    From aioboto3 with Apache License 2.0 5 votes vote down vote up
def from_der_public_key(data: bytes) -> _RSAPublicKey:
        """
        Convert public key in DER encoding to a Public key object

        :param data: public key bytes
        """

        return serialization.load_der_public_key(data, default_backend()) 
Example #4
Source File: ecc.py    From synapse with Apache License 2.0 5 votes vote down vote up
def load(byts):
        '''
        Create a PubKey instance from DER/PKCS8 encoded bytes.

        Args:
            byts (bytes): Bytes to load

        Returns:
            PubKey: A new PubKey instance.
        '''
        return PubKey(c_ser.load_der_public_key(
                byts,
                backend=default_backend())) 
Example #5
Source File: translations.py    From barbican with Apache License 2.0 5 votes vote down vote up
def _convert_public_der_to_pem(der):
    public_key = serialization.load_der_public_key(
        der,
        backend=default_backend()
    )
    pem = public_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo
    )
    return pem 
Example #6
Source File: googleplay.py    From googleplay-api with GNU General Public License v3.0 5 votes vote down vote up
def encryptPassword(self, login, passwd):
        """Encrypt credentials using the google publickey, with the
        RSA algorithm"""

        # structure of the binary key:
        #
        # *-------------------------------------------------------*
        # | modulus_length | modulus | exponent_length | exponent |
        # *-------------------------------------------------------*
        #
        # modulus_length and exponent_length are uint32
        binaryKey = b64decode(config.GOOGLE_PUBKEY)
        # modulus
        i = utils.readInt(binaryKey, 0)
        modulus = utils.toBigInt(binaryKey[4:][0:i])
        # exponent
        j = utils.readInt(binaryKey, i + 4)
        exponent = utils.toBigInt(binaryKey[i + 8:][0:j])

        # calculate SHA1 of the pub key
        digest = hashes.Hash(hashes.SHA1(), backend=default_backend())
        digest.update(binaryKey)
        h = b'\x00' + digest.finalize()[0:4]

        # generate a public key
        der_data = encode_dss_signature(modulus, exponent)
        publicKey = load_der_public_key(der_data, backend=default_backend())

        # encrypt email and password using pubkey
        to_be_encrypted = login.encode() + b'\x00' + passwd.encode()
        ciphertext = publicKey.encrypt(
            to_be_encrypted,
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA1()),
                algorithm=hashes.SHA1(),
                label=None
            )
        )

        return urlsafe_b64encode(h + ciphertext) 
Example #7
Source File: oidc.py    From quay with Apache License 2.0 5 votes vote down vote up
def __missing__(self, kid):
        """
        Loads the public key for this handler from the OIDC service.

        Raises PublicKeyLoadException on failure.
        """
        keys_url = self._login_service._oidc_config()["jwks_uri"]

        # Load the keys.
        try:
            keys = KEYS()
            keys.load_from_url(
                keys_url, verify=not self._login_service.config.get("DEBUGGING", False)
            )
        except Exception as ex:
            logger.exception("Exception loading public key")
            raise PublicKeyLoadException(str(ex))

        # Find the matching key.
        keys_found = keys.by_kid(kid)
        if len(keys_found) == 0:
            raise PublicKeyLoadException("Public key %s not found" % kid)

        rsa_keys = [key for key in keys_found if key.kty == "RSA"]
        if len(rsa_keys) == 0:
            raise PublicKeyLoadException("No RSA form of public key %s not found" % kid)

        matching_key = rsa_keys[0]
        matching_key.deserialize()

        # Reload the key so that we can give a key *instance* to PyJWT to work around its weird parsing
        # issues.
        final_key = load_der_public_key(
            matching_key.key.exportKey("DER"), backend=default_backend()
        )
        self[kid] = final_key
        return final_key 
Example #8
Source File: crypto_common.py    From torpy with Apache License 2.0 5 votes vote down vote up
def rsa_load_der(public_der_data):
    return serialization.load_der_public_key(public_der_data, backend=bend) 
Example #9
Source File: transaction.py    From lbry-sdk with MIT License 5 votes vote down vote up
def is_signature_valid(encoded_signature, signature_digest, public_key_bytes):
        try:
            public_key = load_der_public_key(public_key_bytes, default_backend())
            public_key.verify(encoded_signature, signature_digest, ec.ECDSA(Prehashed(hashes.SHA256())))
            return True
        except (ValueError, InvalidSignature):
            pass
        return False 
Example #10
Source File: registry_access.py    From yotta with Apache License 2.0 5 votes vote down vote up
def getPublicKey(registry=None):
    ''' Return the user's public key (generating and saving a new key pair if necessary) '''
    registry = registry or Registry_Base_URL
    pubkey_pem = None
    if _isPublicRegistry(registry):
        pubkey_pem = settings.getProperty('keys', 'public')
    else:
        for s in _getSources():
            if _sourceMatches(s, registry):
                if 'keys' in s and s['keys'] and 'public' in s['keys']:
                    pubkey_pem = s['keys']['public']
                    break
    if not pubkey_pem:
        pubkey_pem, privatekey_pem = _generateAndSaveKeys()
    else:
        # settings are unicode, we should be able to safely decode to ascii for
        # the key though, as it will either be hex or PEM encoded:
        pubkey_pem = pubkey_pem.encode('ascii')
    # if the key doesn't look like PEM, it might be hex-encided-DER (which we
    # used historically), so try loading that:
    if b'-----BEGIN PUBLIC KEY-----' in pubkey_pem:
        pubkey = serialization.load_pem_public_key(pubkey_pem, default_backend())
    else:
        pubkey_der = binascii.unhexlify(pubkey_pem)
        pubkey = serialization.load_der_public_key(pubkey_der, default_backend())
    return _pubkeyWireFormat(pubkey) 
Example #11
Source File: cert.py    From scapy with GNU General Public License v2.0 5 votes vote down vote up
def import_from_der(self, pubkey):
        # No lib support for explicit curves nor compressed points.
        self.pubkey = serialization.load_der_public_key(pubkey,
                                                        backend=default_backend())  # noqa: E501 
Example #12
Source File: der_serializer.py    From loopchain with Apache License 2.0 5 votes vote down vote up
def load_public_key(cls, cert_public_key: bytes, backend):
        return serialization.load_der_public_key(cert_public_key, backend) 
Example #13
Source File: app_config.py    From dash-masternode-tool with MIT License 5 votes vote down vote up
def get_rpc_encryption_pubkey_object(self):
        if self.__rpc_encryption_pubkey_der:
            if not self.__rpc_encryption_pubkey_object:
                self.__rpc_encryption_pubkey_object = serialization.load_der_public_key(
                    bytes.fromhex(self.__rpc_encryption_pubkey_der), backend=default_backend())
            return self.__rpc_encryption_pubkey_object
        else:
            return None 
Example #14
Source File: authentication.py    From aws-encryption-sdk-python with Apache License 2.0 5 votes vote down vote up
def from_key_bytes(cls, algorithm, key_bytes):
        """Creates a `Verifier` object based on the supplied algorithm and raw verification key.

        :param algorithm: Algorithm on which to base verifier
        :type algorithm: aws_encryption_sdk.identifiers.Algorithm
        :param bytes encoded_point: Raw verification key
        :returns: Instance of Verifier generated from encoded point
        :rtype: aws_encryption_sdk.internal.crypto.Verifier
        """
        return cls(
            algorithm=algorithm, key=serialization.load_der_public_key(data=key_bytes, backend=default_backend())
        ) 
Example #15
Source File: test_mock_key_manager.py    From castellan with Apache License 2.0 5 votes vote down vote up
def get_cryptography_public_key(public_key):
    crypto_public_key = serialization.load_der_public_key(
        bytes(public_key.get_encoded()),
        backend=backends.default_backend())
    return crypto_public_key 
Example #16
Source File: barbican_key_manager.py    From castellan with Apache License 2.0 5 votes vote down vote up
def _get_normalized_payload(self, encoded_bytes, secret_type):
        """Normalizes the bytes of the object.

        Barbican expects certificates, public keys, and private keys in PEM
        format, but Castellan expects these objects to be DER encoded bytes
        instead.
        """
        if secret_type == 'public':
            key = serialization.load_der_public_key(
                encoded_bytes,
                backend=backends.default_backend())
            return key.public_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PublicFormat.SubjectPublicKeyInfo)
        elif secret_type == 'private':
            key = serialization.load_der_private_key(
                encoded_bytes,
                backend=backends.default_backend(),
                password=None)
            return key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.PKCS8,
                encryption_algorithm=serialization.NoEncryption())
        elif secret_type == 'certificate':
            cert = cryptography_x509.load_der_x509_certificate(
                encoded_bytes,
                backend=backends.default_backend())
            return cert.public_bytes(encoding=serialization.Encoding.PEM)
        else:
            return encoded_bytes 
Example #17
Source File: entry.py    From PSPTool with GNU General Public License v3.0 4 votes vote down vote up
def verify_signature(self):
        # Note: This does not work if an entry was compressed AND encrypted.
        # However, we have not yet seen such entry.

        # Only verify signature if we actually have a signature
        if self.signature == None:
            return False

        if self.compressed:
            signed_data = self.get_decompressed()[:self.size_signed + self.header_len]
        elif self.encrypted:
            signed_data = self.get_decrypted()[:self.size_signed + self.header_len]
        else:
            signed_data = self.get_bytes()[:self.size_signed + self.header_len]

        try:
            pubkey_der_encoded = self.pubkey.get_der_encoded()
        except AttributeError:
            print_warning(f"Entry {self.get_readable_type()} is signed, but corresponding pubkey was not found ({self.get_readable_signed_by()})")
            return False

        crypto_pubkey = load_der_public_key(pubkey_der_encoded, backend=default_backend())


        if len(self.signature) == 0x100:
            hash = hashes.SHA256()
            salt_len = 32
        elif len(self.signature) == 0x200:
            hash = hashes.SHA384()
            salt_len = 48
        else:
            print_warning("Weird signature len")
            return False

        try:
            crypto_pubkey.verify(
                self.signature.get_bytes(),
                signed_data,
                padding.PSS(
                    mgf=padding.MGF1(hash),
                    salt_length=salt_len
                ),
                hash
            )
        except InvalidSignature:
            return False

        return True 
Example #18
Source File: ocsp_asn1crypto.py    From snowflake-connector-python with Apache License 2.0 4 votes vote down vote up
def verify_signature(self, signature_algorithm, signature, cert, data):
        use_openssl_only = os.getenv('SF_USE_OPENSSL_ONLY', 'False') == 'True'
        if not use_openssl_only:
            pubkey = asymmetric.load_public_key(cert.public_key).unwrap().dump()
            rsakey = RSA.importKey(pubkey)
            signer = PKCS1_v1_5.new(rsakey)
            if signature_algorithm in SnowflakeOCSPAsn1Crypto.SIGNATURE_ALGORITHM_TO_DIGEST_CLASS:
                digest = \
                    SnowflakeOCSPAsn1Crypto.SIGNATURE_ALGORITHM_TO_DIGEST_CLASS[
                    signature_algorithm].new()
            else:
                # the last resort. should not happen.
                digest = SHA1.new()
            digest.update(data.dump())
            if not signer.verify(digest, signature):
                raise RevocationCheckError(
                    msg="Failed to verify the signature",
                    errno=ER_INVALID_OCSP_RESPONSE)

        else:
            backend = default_backend()
            public_key = serialization.load_der_public_key(cert.public_key.dump(), backend=default_backend())
            if signature_algorithm in SnowflakeOCSPAsn1Crypto.SIGNATURE_ALGORITHM_TO_DIGEST_CLASS:
                chosen_hash = \
                    SnowflakeOCSPAsn1Crypto.SIGNATURE_ALGORITHM_TO_DIGEST_CLASS_OPENSSL[
                        signature_algorithm]()
            else:
                # the last resort. should not happen.
                chosen_hash = hashes.SHA1()
            hasher = hashes.Hash(chosen_hash, backend)
            hasher.update(data.dump())
            digest = hasher.finalize()
            try:
                public_key.verify(
                    signature,
                    digest,
                    padding.PKCS1v15(),
                    utils.Prehashed(chosen_hash)
                )
            except InvalidSignature:
                raise RevocationCheckError(
                    msg="Failed to verify the signature",
                    errno=ER_INVALID_OCSP_RESPONSE) 
Example #19
Source File: test_crypto.py    From barbican with Apache License 2.0 4 votes vote down vote up
def test_generate_1024_bit_DSA_key_with_passphrase(self):
        generate_dto = plugin.GenerateDTO('dsa', 1024, None, 'changeme')
        kek_meta_dto = self._get_mocked_kek_meta_dto()

        private_dto, public_dto, passwd_dto = self.plugin.generate_asymmetric(
            generate_dto,
            kek_meta_dto,
            mock.MagicMock()
        )

        decrypt_dto = plugin.DecryptDTO(private_dto.cypher_text)
        private_dto = self.plugin.decrypt(decrypt_dto,
                                          kek_meta_dto,
                                          private_dto.kek_meta_extended,
                                          mock.MagicMock())

        decrypt_dto = plugin.DecryptDTO(public_dto.cypher_text)
        public_dto = self.plugin.decrypt(decrypt_dto,
                                         kek_meta_dto,
                                         public_dto.kek_meta_extended,
                                         mock.MagicMock())

        # check we can reload the private and public keys
        private_key = serialization.load_der_private_key(
            data=private_dto,
            password='changeme'.encode(),
            backend=default_backend()
        )

        public_key = serialization.load_der_public_key(
            data=public_dto,
            backend=default_backend()
        )

        self.assertEqual(1024, private_key.key_size)
        self.assertEqual(1024, public_key.key_size)

        public_key = public_key.public_bytes(
            encoding=serialization.Encoding.DER,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        )

        # get the public key from the private key we recovered to compare
        recovered_key = private_key.public_key().public_bytes(
            encoding=serialization.Encoding.DER,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        )

        self.assertTrue(public_key == recovered_key) 
Example #20
Source File: __init__.py    From signxml with Apache License 2.0 4 votes vote down vote up
def _verify_signature_with_pubkey(self, signed_info_c14n, raw_signature, key_value, der_encoded_key_value,
                                      signature_alg):
        if der_encoded_key_value is not None:
            key = load_der_public_key(b64decode(der_encoded_key_value.text), backend=default_backend())
        if "ecdsa-" in signature_alg:
            if key_value is not None:
                ec_key_value = self._find(key_value, "ECKeyValue", namespace="dsig11")
                named_curve = self._find(ec_key_value, "NamedCurve", namespace="dsig11")
                public_key = self._find(ec_key_value, "PublicKey", namespace="dsig11")
                key_data = b64decode(public_key.text)[1:]
                x = bytes_to_long(key_data[:len(key_data)//2])
                y = bytes_to_long(key_data[len(key_data)//2:])
                curve_class = self.known_ecdsa_curves[named_curve.get("URI")]
                key = ec.EllipticCurvePublicNumbers(x=x, y=y, curve=curve_class()).public_key(backend=default_backend())
            elif not isinstance(key, ec.EllipticCurvePublicKey):
                raise InvalidInput("DER encoded key value does not match specified signature algorithm")
            dss_signature = self._encode_dss_signature(raw_signature, key.key_size)
            key.verify(
                dss_signature,
                data=signed_info_c14n,
                signature_algorithm=ec.ECDSA(
                    self._get_signature_digest_method(signature_alg)
                ),
            )
        elif "dsa-" in signature_alg:
            if key_value is not None:
                dsa_key_value = self._find(key_value, "DSAKeyValue")
                p = self._get_long(dsa_key_value, "P")
                q = self._get_long(dsa_key_value, "Q")
                g = self._get_long(dsa_key_value, "G", require=False)
                y = self._get_long(dsa_key_value, "Y")
                pn = dsa.DSAPublicNumbers(y=y, parameter_numbers=dsa.DSAParameterNumbers(p=p, q=q, g=g))
                key = pn.public_key(backend=default_backend())
            elif not isinstance(key, dsa.DSAPublicKey):
                raise InvalidInput("DER encoded key value does not match specified signature algorithm")
            # TODO: supply meaningful key_size_bits for signature length assertion
            dss_signature = self._encode_dss_signature(raw_signature, len(raw_signature) * 8 / 2)
            key.verify(dss_signature,
                       data=signed_info_c14n,
                       algorithm=self._get_signature_digest_method(signature_alg))
        elif "rsa-" in signature_alg:
            if key_value is not None:
                rsa_key_value = self._find(key_value, "RSAKeyValue")
                modulus = self._get_long(rsa_key_value, "Modulus")
                exponent = self._get_long(rsa_key_value, "Exponent")
                key = rsa.RSAPublicNumbers(e=exponent, n=modulus).public_key(backend=default_backend())
            elif not isinstance(key, rsa.RSAPublicKey):
                raise InvalidInput("DER encoded key value does not match specified signature algorithm")
            key.verify(raw_signature,
                       data=signed_info_c14n,
                       padding=PKCS1v15(),
                       algorithm=self._get_signature_digest_method(signature_alg))
        else:
            raise NotImplementedError() 
Example #21
Source File: detect.py    From roca with MIT License 4 votes vote down vote up
def process_pem_rsakey(self, data, name, idx):
        """
        Processes PEM encoded RSA key
        :param data:
        :param name:
        :param idx:
        :return:
        """
        from cryptography.hazmat.primitives.serialization import load_der_public_key
        from cryptography.hazmat.primitives.serialization import load_der_private_key
        try:
            if startswith(data, '-----BEGIN RSA PUBLIC KEY') or startswith(data, '-----BEGIN PUBLIC KEY'):
                rsa = load_der_public_key(pem_to_der(data), self.get_backend())
                public_numbers = rsa.public_numbers()
            elif startswith(data, '-----BEGIN RSA PRIVATE KEY') or startswith(data, '-----BEGIN PRIVATE KEY'):
                rsa = load_der_private_key(pem_to_der(data), None, self.get_backend())
                public_numbers = rsa.private_numbers().public_numbers
            else:
                return None
            self.num_rsa_keys += 1
            self.num_rsa += 1

            js = collections.OrderedDict()
            js['type'] = 'pem-rsa-key'
            js['fname'] = name
            js['idx'] = idx
            js['pem'] = data
            js['e'] = '0x%x' % public_numbers.e
            js['n'] = '0x%x' % public_numbers.n

            if self.has_fingerprint(public_numbers.n):
                logger.warning('Fingerprint found in PEM RSA key %s ' % name)
                self.mark_and_add_effort(public_numbers.n, js)

                if self.do_print:
                    print(json.dumps(js))

            return TestResult(js)

        except Exception as e:
            logger.debug('Pubkey loading error: %s : %s [%s] : %s' % (name, idx, data[:20], e))
            self.trace_logger.log(e) 
Example #22
Source File: __init__.py    From stem with GNU Lesser General Public License v3.0 4 votes vote down vote up
def _digest_for_signature(self, signing_key: str, signature: str) -> str:
    """
    Provides the signed digest we should have given this key and signature.

    :param signing_key: key block used to make this signature
    :param signature: signed digest for this descriptor content

    :returns: the digest string encoded in uppercase hex

    :raises: ValueError if unable to provide a validly signed digest
    """

    try:
      from cryptography.hazmat.backends import default_backend
      from cryptography.hazmat.primitives.serialization import load_der_public_key
      from cryptography.utils import int_to_bytes, int_from_bytes
    except ImportError:
      raise ValueError('Generating the signed digest requires the cryptography module')

    key = load_der_public_key(_bytes_for_block(signing_key), default_backend())
    modulus = key.public_numbers().n
    public_exponent = key.public_numbers().e

    sig_as_bytes = _bytes_for_block(signature)
    sig_as_long = int_from_bytes(sig_as_bytes, byteorder='big')  # convert signature to an int
    blocksize = len(sig_as_bytes)  # 256B for NetworkStatusDocuments, 128B for others

    # use the public exponent[e] & the modulus[n] to decrypt the int
    decrypted_int = pow(sig_as_long, public_exponent, modulus)

    # convert the int to a byte array
    decrypted_bytes = int_to_bytes(decrypted_int, blocksize)

    ############################################################################
    # The decrypted bytes should have a structure exactly along these lines.
    # 1 byte  - [null '\x00']
    # 1 byte  - [block type identifier '\x01'] - Should always be 1
    # N bytes - [padding '\xFF' ]
    # 1 byte  - [separator '\x00' ]
    # M bytes - [message]
    # Total   - 128 bytes
    # More info here http://www.ietf.org/rfc/rfc2313.txt
    #                esp the Notes in section 8.1
    ############################################################################

    try:
      if decrypted_bytes.index(DIGEST_TYPE_INFO) != 0:
        raise ValueError('Verification failed, identifier missing')
    except ValueError:
      raise ValueError('Verification failed, malformed data')

    try:
      identifier_offset = 2

      # find the separator
      seperator_index = decrypted_bytes.index(DIGEST_SEPARATOR, identifier_offset)
    except ValueError:
      raise ValueError('Verification failed, seperator not found')

    digest_hex = codecs.encode(decrypted_bytes[seperator_index + 1:], 'hex_codec')
    return stem.util.str_tools._to_unicode(digest_hex.upper())