Python cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicNumbers() Examples

The following are 30 code examples of cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicNumbers(). 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.asymmetric.rsa , or try the search function .
Example #1
Source File: service.py    From lemur with Apache License 2.0 6 votes vote down vote up
def get_rsa_public_key(n, e):
    """
    Retrieve an RSA public key based on a module and exponent as provided by the JWKS format.

    :param n:
    :param e:
    :return: a RSA Public Key in PEM format
    """
    n = int(binascii.hexlify(jwt.utils.base64url_decode(bytes(n, "utf-8"))), 16)
    e = int(binascii.hexlify(jwt.utils.base64url_decode(bytes(e, "utf-8"))), 16)

    pub = RSAPublicNumbers(e, n).public_key(default_backend())
    return pub.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo,
    ) 
Example #2
Source File: test_powershell.py    From pypsrp with MIT License 6 votes vote down vote up
def gen_rsa_keypair(public_exponent, key_size, backend):
    # for a pasing test against mocked results, we need the same key
    # for each run

    # private key numbers
    d = 21617696977064831737076881102083866512588021127782856037972563073160418492784722157229048881139551797965254106994729989171004895438848876105403145818526588448619012753150859908505079457128264842711189718538434996465875355972895683414261775421352553376878242391757860294122032733780201193753125763293334069627997366690578378643268496972715558088736335242616446993490560907175346811363459760219154246765368454269083276034064771683561116425318584728938420495690895295417261302673227504350398337950587166908640861984752151206832712112769733009288056773792011545187027621461752928443722277452545442134981026071169761569129
    dmp1 = 129490813503009185789974379255770561425157574567257502592607367628590256916193790244618544180042259447193585640234142495635548617466553819050739804131538251753363069954266652888546939369520788464015077722316584767752481491358983245279072645160828476778216654224017198857901235711822454725809127201111535934753
    dmq1 = 48648800397834409354931458481260042874431001732145738308246185682766008281764239801132482123299506611633669689538582946696791307965087683313609603490735622965494394760749284568774366017328170855872209094830510839953297302962573968041079091285470051311421587284299491265676844471173504726139132522742725727613
    iqmp = 39631089624266744377721024140775526581242717587318543319284349361749959043577498327792652579346928867008103676271384098405811933888254575054903735904994321302658687548878487654303384553639708412577672820397125886631056454780398875240593971733447420281054575014889376749144359968455995345232769795875325417317
    p = 174331130742537243408330955079815843963035167715989214203198624738597363753422194561659111132445142920926993058833709875440980890363712769908141629896643845627776407469038077862709547359496382776626050712560846670587394813048350142683947903572416102765283173128172045224943986952459084128294017448217886823253
    q = 141639112913055250372907285405879139487409354087944702421480687298597773645578986399236760591500655922107321654521995138945695777437048045372013886449237695348272152351631535441304559114954968164429007883070066144736528002854651716726263900736377199146896337887655964419309789253989248300176824884184363216819

    # public key numbers
    e = 65537
    n = 24692106711502830011203227021058444318027801046612842012663747949974978593541529463344548800446917862266219189049856550539417324579114258210080798360122994007305091566363663241781504651372764226027210216355916383975880112316706422502404691353489765771310270171473497918954906308690817673196552680498374521519566949221302301125182104198985782657283395055909134373469597836420671163965867038455758131344733786842283328454828820406016508955409107145350345035248825315933976893356673777910251028486191789752627573225093968284278302684745743589192378470115772764709506475265246795419324395050366115533203601201395969892207

    public_numbers = rsa.RSAPublicNumbers(e, n)
    numbers = rsa.RSAPrivateNumbers(p, q, d, dmp1, dmq1, iqmp,
                                    public_numbers)
    key = default_backend().load_rsa_private_numbers(numbers)

    return key 
Example #3
Source File: test_host.py    From pypsrp with MIT License 6 votes vote down vote up
def gen_rsa_keypair(public_exponent, key_size, backend):
    # for a pasing test against mocked results, we need the same key
    # for each run

    # private key numbers
    d = 21617696977064831737076881102083866512588021127782856037972563073160418492784722157229048881139551797965254106994729989171004895438848876105403145818526588448619012753150859908505079457128264842711189718538434996465875355972895683414261775421352553376878242391757860294122032733780201193753125763293334069627997366690578378643268496972715558088736335242616446993490560907175346811363459760219154246765368454269083276034064771683561116425318584728938420495690895295417261302673227504350398337950587166908640861984752151206832712112769733009288056773792011545187027621461752928443722277452545442134981026071169761569129
    dmp1 = 129490813503009185789974379255770561425157574567257502592607367628590256916193790244618544180042259447193585640234142495635548617466553819050739804131538251753363069954266652888546939369520788464015077722316584767752481491358983245279072645160828476778216654224017198857901235711822454725809127201111535934753
    dmq1 = 48648800397834409354931458481260042874431001732145738308246185682766008281764239801132482123299506611633669689538582946696791307965087683313609603490735622965494394760749284568774366017328170855872209094830510839953297302962573968041079091285470051311421587284299491265676844471173504726139132522742725727613
    iqmp = 39631089624266744377721024140775526581242717587318543319284349361749959043577498327792652579346928867008103676271384098405811933888254575054903735904994321302658687548878487654303384553639708412577672820397125886631056454780398875240593971733447420281054575014889376749144359968455995345232769795875325417317
    p = 174331130742537243408330955079815843963035167715989214203198624738597363753422194561659111132445142920926993058833709875440980890363712769908141629896643845627776407469038077862709547359496382776626050712560846670587394813048350142683947903572416102765283173128172045224943986952459084128294017448217886823253
    q = 141639112913055250372907285405879139487409354087944702421480687298597773645578986399236760591500655922107321654521995138945695777437048045372013886449237695348272152351631535441304559114954968164429007883070066144736528002854651716726263900736377199146896337887655964419309789253989248300176824884184363216819

    # public key numbers
    e = 65537
    n = 24692106711502830011203227021058444318027801046612842012663747949974978593541529463344548800446917862266219189049856550539417324579114258210080798360122994007305091566363663241781504651372764226027210216355916383975880112316706422502404691353489765771310270171473497918954906308690817673196552680498374521519566949221302301125182104198985782657283395055909134373469597836420671163965867038455758131344733786842283328454828820406016508955409107145350345035248825315933976893356673777910251028486191789752627573225093968284278302684745743589192378470115772764709506475265246795419324395050366115533203601201395969892207

    public_numbers = rsa.RSAPublicNumbers(e, n)
    numbers = rsa.RSAPrivateNumbers(p, q, d, dmp1, dmq1, iqmp,
                                    public_numbers)
    key = default_backend().load_rsa_private_numbers(numbers)

    return key 
Example #4
Source File: rsa_crypto.py    From jx-sqlite with Mozilla Public License 2.0 6 votes vote down vote up
def verify(signed, public_key):
    data = base642bytes(signed.data)
    signature = base642bytes(signed.signature)

    key = RSAPublicNumbers(
        public_key.e,
        base642int(public_key.n)
    ).public_key(BACKEND)

    key.verify(
        signature=signature,
        data=data,
        padding=PADDING.get(signed.padding, PSS),
        algorithm=ALGORITHM.get(signed.algorithm, SHA256),
    )

    return json2value(data.decode("utf8")) 
Example #5
Source File: rsakey.py    From imoocc with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, msg=None, data=None, filename=None, password=None, key=None, file_obj=None):
        self.key = None
        if file_obj is not None:
            self._from_private_key(file_obj, password)
            return
        if filename is not None:
            self._from_private_key_file(filename, password)
            return
        if (msg is None) and (data is not None):
            msg = Message(data)
        if key is not None:
            self.key = key
        else:
            if msg is None:
                raise SSHException('Key object may not be empty')
            if msg.get_text() != 'ssh-rsa':
                raise SSHException('Invalid key')
            self.key = rsa.RSAPublicNumbers(
                e=msg.get_mpint(), n=msg.get_mpint()
            ).public_key(default_backend()) 
Example #6
Source File: cert.py    From scapy with GNU General Public License v2.0 6 votes vote down vote up
def fill_and_store(self, modulus=None, modulusLen=None, pubExp=None):
        pubExp = pubExp or 65537
        if not modulus:
            real_modulusLen = modulusLen or 2048
            private_key = rsa.generate_private_key(public_exponent=pubExp,
                                                   key_size=real_modulusLen,
                                                   backend=default_backend())
            self.pubkey = private_key.public_key()
        else:
            real_modulusLen = len(binrepr(modulus))
            if modulusLen and real_modulusLen != modulusLen:
                warning("modulus and modulusLen do not match!")
            pubNum = rsa.RSAPublicNumbers(n=modulus, e=pubExp)
            self.pubkey = pubNum.public_key(default_backend())
        # Lines below are only useful for the legacy part of pkcs1.py
        pubNum = self.pubkey.public_numbers()
        self._modulusLen = real_modulusLen
        self._modulus = pubNum.n
        self._pubExp = pubNum.e 
Example #7
Source File: test_RSA.py    From python-jose with MIT License 5 votes vote down vote up
def test_cryptography_RSA_key_instance():

    key = pyca_rsa.RSAPublicNumbers(
        long(65537),
        long(26057131595212989515105618545799160306093557851986992545257129318694524535510983041068168825614868056510242030438003863929818932202262132630250203397069801217463517914103389095129323580576852108653940669240896817348477800490303630912852266209307160550655497615975529276169196271699168537716821419779900117025818140018436554173242441334827711966499484119233207097432165756707507563413323850255548329534279691658369466534587631102538061857114141268972476680597988266772849780811214198186940677291891818952682545840788356616771009013059992237747149380197028452160324144544057074406611859615973035412993832273216732343819),
    ).public_key(default_backend())

    pubkey = CryptographyRSAKey(key, ALGORITHMS.RS256)
    assert pubkey.is_public()

    pem = pubkey.to_pem()
    assert pem.startswith(b'-----BEGIN PUBLIC KEY-----') 
Example #8
Source File: test_engine.py    From PyKMIP with Apache License 2.0 5 votes vote down vote up
def test_verify_signature_invalid_signature(self):
        """
        Test that verifying an invalid signature returns the right value.
        """
        engine = crypto.CryptographyEngine()

        backend = backends.default_backend()
        public_key_numbers = rsa.RSAPublicNumbers(
            int('010001', 16),
            int(
                'ac13d9fdae7b7335b69cd98567e9647d99bf373a9e05ce3435d66465f328'
                'b7f7334b792aee7efa044ebc4c7a30b21a5d7a89cdb3a30dfcd9fee9995e'
                '09415edc0bf9e5b4c3f74ff53fb4d29441bf1b7ed6cbdd4a47f9252269e1'
                '646f6c1aee0514e93f6cb9df71d06c060a2104b47b7260ac37c106861dc7'
                '8ca5a25faa9cb2e3',
                16)
        )
        public_key = public_key_numbers.public_key(backend)
        public_bytes = public_key.public_bytes(
            serialization.Encoding.PEM,
            serialization.PublicFormat.PKCS1
        )

        args = (
            public_bytes,
            b'',
            b'',
            enums.PaddingMethod.PSS
        )
        kwargs = {
            'signing_algorithm': enums.CryptographicAlgorithm.RSA,
            'hashing_algorithm': enums.HashingAlgorithm.SHA_1,
            'digital_signature_algorithm': None
        }
        self.assertFalse(
            engine.verify_signature(*args, **kwargs)
        ) 
Example #9
Source File: test_engine.py    From PyKMIP with Apache License 2.0 5 votes vote down vote up
def test_verify_signature(signature_parameters):
    """
    Test that various signature verification methods and settings can be used
    to correctly verify signatures.
    """
    engine = crypto.CryptographyEngine()

    backend = backends.default_backend()
    public_key_numbers = rsa.RSAPublicNumbers(
        signature_parameters.get('public_key').get('e'),
        signature_parameters.get('public_key').get('n')
    )
    public_key = public_key_numbers.public_key(backend)
    public_bytes = public_key.public_bytes(
        signature_parameters.get('encoding'),
        serialization.PublicFormat.PKCS1
    )

    result = engine.verify_signature(
        signing_key=public_bytes,
        message=signature_parameters.get('message'),
        signature=signature_parameters.get('signature'),
        padding_method=signature_parameters.get('padding_method'),
        signing_algorithm=signature_parameters.get('signing_algorithm'),
        hashing_algorithm=signature_parameters.get('hashing_algorithm'),
        digital_signature_algorithm=signature_parameters.get(
            'digital_signature_algorithm'
        )
    )

    assert result 
Example #10
Source File: jwtutil.py    From quay with Apache License 2.0 5 votes vote down vote up
def jwk_dict_to_public_key(jwk):
    """
    Converts the specified JWK into a public key.
    """
    jwkest_key = keyrep(jwk)
    if isinstance(jwkest_key, RSAKey):
        pycrypto_key = jwkest_key.key
        return RSAPublicNumbers(e=pycrypto_key.e, n=pycrypto_key.n).public_key(default_backend())
    elif isinstance(jwkest_key, ECKey):
        x, y = jwkest_key.get_key()
        return EllipticCurvePublicNumbers(x, y, jwkest_key.curve).public_key(default_backend())

    raise Exception("Unsupported kind of JWK: %s", str(type(jwkest_key))) 
Example #11
Source File: pubkey.py    From python-smime with Apache License 2.0 5 votes vote down vote up
def __init__(self, public_key_info):
        rsaparams = public_key_info['public_key'].native
        key = rsa.RSAPublicNumbers(rsaparams['public_exponent'], rsaparams['modulus'])
        backend = default_backend()
        self._cipher = key.public_key(backend)
        self._padding = padding.PKCS1v15() 
Example #12
Source File: cryptography_backend.py    From python-jose with MIT License 5 votes vote down vote up
def _process_jwk(self, jwk_dict):
        if not jwk_dict.get('kty') == 'RSA':
            raise JWKError("Incorrect key type. Expected: 'RSA', Received: %s" % jwk_dict.get('kty'))

        e = base64_to_long(jwk_dict.get('e', 256))
        n = base64_to_long(jwk_dict.get('n'))
        public = rsa.RSAPublicNumbers(e, n)

        if 'd' not in jwk_dict:
            return public.public_key(self.cryptography_backend())
        else:
            # This is a private key.
            d = base64_to_long(jwk_dict.get('d'))

            extra_params = ['p', 'q', 'dp', 'dq', 'qi']

            if any(k in jwk_dict for k in extra_params):
                # Precomputed private key parameters are available.
                if not all(k in jwk_dict for k in extra_params):
                    # These values must be present when 'p' is according to
                    # Section 6.3.2 of RFC7518, so if they are not we raise
                    # an error.
                    raise JWKError('Precomputed private key parameters are incomplete.')

                p = base64_to_long(jwk_dict['p'])
                q = base64_to_long(jwk_dict['q'])
                dp = base64_to_long(jwk_dict['dp'])
                dq = base64_to_long(jwk_dict['dq'])
                qi = base64_to_long(jwk_dict['qi'])
            else:
                # The precomputed private key parameters are not available,
                # so we use cryptography's API to fill them in.
                p, q = rsa.rsa_recover_prime_factors(n, e, d)
                dp = rsa.rsa_crt_dmp1(d, p)
                dq = rsa.rsa_crt_dmq1(d, q)
                qi = rsa.rsa_crt_iqmp(p, q)

            private = rsa.RSAPrivateNumbers(p, q, d, dp, dq, qi, public)

            return private.private_key(self.cryptography_backend()) 
Example #13
Source File: ssh.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _load_ssh_rsa_public_key(key_type, decoded_data, backend):
    e, rest = _ssh_read_next_mpint(decoded_data)
    n, rest = _ssh_read_next_mpint(rest)

    if rest:
        raise ValueError('Key body contains extra bytes.')

    return rsa.RSAPublicNumbers(e, n).public_key(backend) 
Example #14
Source File: fields.py    From PGPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __pubkey__(self):
        return rsa.RSAPublicNumbers(self.e, self.n).public_key(default_backend()) 
Example #15
Source File: fields.py    From PGPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __privkey__(self):
        return rsa.RSAPrivateNumbers(self.p, self.q, self.d,
                                     rsa.rsa_crt_dmp1(self.d, self.p),
                                     rsa.rsa_crt_dmq1(self.d, self.q),
                                     rsa.rsa_crt_iqmp(self.p, self.q),
                                     rsa.RSAPublicNumbers(self.e, self.n)).private_key(default_backend()) 
Example #16
Source File: serialization.py    From quickstart-git2s3 with Apache License 2.0 5 votes vote down vote up
def _load_ssh_rsa_public_key(key_type, decoded_data, backend):
    e, rest = _ssh_read_next_mpint(decoded_data)
    n, rest = _ssh_read_next_mpint(rest)

    if rest:
        raise ValueError('Key body contains extra bytes.')

    return rsa.RSAPublicNumbers(e, n).public_key(backend) 
Example #17
Source File: rsa_public_key.py    From bless with Apache License 2.0 5 votes vote down vote up
def __init__(self, ssh_public_key):
        """
        Extracts the useful RSA Public Key information from an SSH Public Key file.
        :param ssh_public_key: SSH Public Key file contents. (i.e. 'ssh-rsa AAAAB3NzaC1yc2E..').
        """
        super(RSAPublicKey, self).__init__()

        self.type = SSHPublicKeyType.RSA

        split_ssh_public_key = ssh_public_key.split(' ')
        split_key_len = len(split_ssh_public_key)

        # is there a key comment at the end?
        if split_key_len > 2:
            self.key_comment = ' '.join(split_ssh_public_key[2:])
        else:
            self.key_comment = ''

        public_key = serialization.load_ssh_public_key(ssh_public_key.encode('ascii'), default_backend())
        ca_pub_numbers = public_key.public_numbers()
        if not isinstance(ca_pub_numbers, RSAPublicNumbers):
            raise TypeError("Public Key is not the correct type or format")

        self.key_size = public_key.key_size
        self.e = ca_pub_numbers.e
        self.n = ca_pub_numbers.n

        key_bytes = base64.b64decode(split_ssh_public_key[1])
        fingerprint = hashlib.md5(key_bytes).hexdigest()

        self.fingerprint = 'RSA ' + ':'.join(
            fingerprint[i:i + 2] for i in range(0, len(fingerprint), 2)) 
Example #18
Source File: cli.py    From dcos with Apache License 2.0 5 votes vote down vote up
def dcos_adminrouter(b, opts):
    b.cluster_id()

    # Require the IAM to already be up and running. The IAM contains logic for
    # achieving consensus about a key pair, and exposes the public key
    # information via its JWKS endpoint. Talk directly to the local IAM instance
    # which is reachable via the local network interface.
    r = requests.get('http://127.0.0.1:8101/acs/api/v1/auth/jwks')

    if r.status_code != 200:
        log.info('JWKS retrieval failed. Got %s with body: %s', r, r.text)
        sys.exit(1)

    jwks = r.json()

    # The first key in the JSON Web Key Set corresponds to the current private
    # key used for signing authentiction tokens.
    key = jwks['keys'][0]

    exponent_bytes = base64url_decode(key['e'].encode('ascii'))
    exponent_int = bytes_to_number(exponent_bytes)
    modulus_bytes = base64url_decode(key['n'].encode('ascii'))
    modulus_int = bytes_to_number(modulus_bytes)
    # Generate a `cryptography` public key object instance from these numbers.
    public_numbers = rsa.RSAPublicNumbers(n=modulus_int, e=exponent_int)
    public_key = public_numbers.public_key(
        backend=cryptography.hazmat.backends.default_backend())

    # Serialize public key into the OpenSSL PEM public key format RFC 5280).
    pubkey_pem_bytes = public_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo)

    rundir = utils.dcos_run_path / 'dcos-adminrouter'
    rundir.mkdir(parents=True, exist_ok=True)
    pubkey_path = rundir / 'auth-token-verification-key'
    utils.write_public_file(pubkey_path, pubkey_pem_bytes)
    utils.chown(pubkey_path, user='dcos_adminrouter') 
Example #19
Source File: ssh.py    From quickstart-redhat-openshift with Apache License 2.0 5 votes vote down vote up
def _load_ssh_rsa_public_key(key_type, decoded_data, backend):
    e, rest = _ssh_read_next_mpint(decoded_data)
    n, rest = _ssh_read_next_mpint(rest)

    if rest:
        raise ValueError('Key body contains extra bytes.')

    return rsa.RSAPublicNumbers(e, n).public_key(backend) 
Example #20
Source File: ssh.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _load_ssh_rsa_public_key(key_type, decoded_data, backend):
    e, rest = _ssh_read_next_mpint(decoded_data)
    n, rest = _ssh_read_next_mpint(rest)

    if rest:
        raise ValueError('Key body contains extra bytes.')

    return rsa.RSAPublicNumbers(e, n).public_key(backend) 
Example #21
Source File: ssh.py    From teleport with Apache License 2.0 5 votes vote down vote up
def _load_ssh_rsa_public_key(key_type, decoded_data, backend):
    e, rest = _ssh_read_next_mpint(decoded_data)
    n, rest = _ssh_read_next_mpint(rest)

    if rest:
        raise ValueError('Key body contains extra bytes.')

    return rsa.RSAPublicNumbers(e, n).public_key(backend) 
Example #22
Source File: jwk.py    From jwcrypto with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _rsa_pub(self, k):
        return rsa.RSAPublicNumbers(self._decode_int(k['e']),
                                    self._decode_int(k['n'])) 
Example #23
Source File: keys.py    From ivre with GNU General Public License v3.0 5 votes vote down vote up
def _rsa_construct(exp, mod):
    return RSAPublicNumbers(exp, mod).public_key(default_backend()) 
Example #24
Source File: serialization.py    From oss-ftp with MIT License 5 votes vote down vote up
def _load_ssh_rsa_public_key(key_type, decoded_data, backend):
    e, rest = _read_next_mpint(decoded_data)
    n, rest = _read_next_mpint(rest)

    if rest:
        raise ValueError('Key body contains extra bytes.')

    return rsa.RSAPublicNumbers(e, n).public_key(backend) 
Example #25
Source File: detect.py    From roca with MIT License 5 votes vote down vote up
def default_classic(self, o):
        from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicNumbers

        if isinstance(o, set):
            return list(o)
        elif isinstance(o, RSAPublicNumbers):
            return {'n': o.n, 'e': o.e}
        else:
            return super(AutoJSONEncoder, self).default(o) 
Example #26
Source File: serialization.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _load_ssh_rsa_public_key(key_type, decoded_data, backend):
    e, rest = _ssh_read_next_mpint(decoded_data)
    n, rest = _ssh_read_next_mpint(rest)

    if rest:
        raise ValueError('Key body contains extra bytes.')

    return rsa.RSAPublicNumbers(e, n).public_key(backend) 
Example #27
Source File: serialization.py    From teleport with Apache License 2.0 5 votes vote down vote up
def _load_ssh_rsa_public_key(key_type, decoded_data, backend):
    e, rest = _ssh_read_next_mpint(decoded_data)
    n, rest = _ssh_read_next_mpint(rest)

    if rest:
        raise ValueError('Key body contains extra bytes.')

    return rsa.RSAPublicNumbers(e, n).public_key(backend) 
Example #28
Source File: _robot_tester.py    From sslyze with GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_rsa_parameters(server_info: ServerConnectivityInfo, openssl_cipher_string: str) -> Optional[RSAPublicNumbers]:
    ssl_connection = server_info.get_preconfigured_tls_connection()
    ssl_connection.ssl_client.set_cipher_list(openssl_cipher_string)
    parsed_cert = None
    try:
        # Perform the SSL handshake
        ssl_connection.connect()
        cert_as_pem = ssl_connection.ssl_client.get_received_chain()[0]
        parsed_cert = load_pem_x509_certificate(cert_as_pem.encode("ascii"), backend=default_backend())
    except ServerRejectedTlsHandshake:
        # Server does not support RSA cipher suites?
        pass
    except ClientCertificateRequested:
        # AD: The server asked for a client cert. We could still retrieve the server certificate, but it is unclear
        # to me if the ROBOT check is supposed to work even if we do not provide a client cert. My guess is that
        # it should not work since it requires completing a full handshake, which we can't without a client cert.
        # Hence, propagate the error to make the check fail.
        raise
    finally:
        ssl_connection.close()

    if parsed_cert:
        public_key = parsed_cert.public_key()
        if isinstance(public_key, RSAPublicKey):
            return public_key.public_numbers()
        else:
            return None
    else:
        return None 
Example #29
Source File: ssh.py    From teleport with Apache License 2.0 5 votes vote down vote up
def _load_ssh_rsa_public_key(key_type, decoded_data, backend):
    e, rest = _ssh_read_next_mpint(decoded_data)
    n, rest = _ssh_read_next_mpint(rest)

    if rest:
        raise ValueError('Key body contains extra bytes.')

    return rsa.RSAPublicNumbers(e, n).public_key(backend) 
Example #30
Source File: rsa.py    From securesystemslib with MIT License 5 votes vote down vote up
def create_pubkey(pubkey_info):
  """
  <Purpose>
    Create and return an RSAPublicKey object from the passed pubkey_info
    using pyca/cryptography.

  <Arguments>
    pubkey_info:
            The RSA pubkey info dictionary as specified by
            securesystemslib.formats.GPG_RSA_PUBKEY_SCHEMA

  <Exceptions>
    securesystemslib.exceptions.FormatError if
      pubkey_info does not match securesystemslib.formats.GPG_RSA_PUBKEY_SCHEMA

    securesystemslib.exceptions.UnsupportedLibraryError if
      the cryptography module is unavailable

  <Returns>
    A cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey based on the
    passed pubkey_info.

  """
  if not CRYPTO: # pragma: no cover
    raise securesystemslib.exceptions.UnsupportedLibraryError(NO_CRYPTO_MSG)

  securesystemslib.formats.GPG_RSA_PUBKEY_SCHEMA.check_match(pubkey_info)

  e = int(pubkey_info['keyval']['public']['e'], 16)
  n = int(pubkey_info['keyval']['public']['n'], 16)
  pubkey = rsa.RSAPublicNumbers(e, n).public_key(backends.default_backend())

  return pubkey