Extract an RSA key from a PEM-encoded X.509 certificate

    :param pem_data: RSA key encoded in standard form
    :return: rsa.RSAPublicKey instance
489226
def import_rsa_key(pem_data):
    
    if not pem_data.startswith(PREFIX):
        pem_data = bytes('{}\n{}\n{}'.format(PREFIX, pem_data, POSTFIX),
                         'utf-8')
    else:
        pem_data = bytes(pem_data, 'utf-8')
    cert = x509.load_pem_x509_certificate(pem_data, default_backend())
    return cert.public_key()
877890
def process_pem(self, data, name):
        
        try:
            ret = []
            data = to_string(data)
            parts = re.split(r'-----BEGIN', data)
            if len(parts) == 0:
                return None

            if len(parts[0]) == 0:
                parts.pop(0)

            crt_arr = ['-----BEGIN' + x for x in parts]
            for idx, pem_rec in enumerate(crt_arr):
                pem_rec = pem_rec.strip()
                if len(pem_rec) == 0:
                    continue

                if startswith(pem_rec, '-----BEGIN CERTIFICATE REQUEST'):
                    return self.process_pem_csr(pem_rec, name, idx)
                elif startswith(pem_rec, '-----BEGIN CERTIF'):
                    return self.process_pem_cert(pem_rec, name, idx)
                elif startswith(pem_rec, '-----BEGIN '):  # fallback
                    return self.process_pem_rsakey(pem_rec, name, idx)
            return ret

        except Exception as e:
            logger.debug('Exception processing PEM file %s : %s' % (name, e))
            self.trace_logger.log(e)
        return None
1191541
def process_pem_rsakey(self, data, name, idx):
        
        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)
221479
public static RSAPublicKey parseRSAPublicKey(String pem)
            throws CertificateException, UnsupportedEncodingException,
            ServletException {
        String PEM_HEADER = "-----BEGIN CERTIFICATE-----\n";
        String PEM_FOOTER = "\n-----END CERTIFICATE-----";
        String fullPem = PEM_HEADER + pem + PEM_FOOTER;
        PublicKey key = null;
        try {
            CertificateFactory fact = CertificateFactory.getInstance("X.509");
            ByteArrayInputStream is = new ByteArrayInputStream(fullPem.getBytes("UTF8"));
            X509Certificate cer = (X509Certificate) fact.generateCertificate(is);
            key = cer.getPublicKey();
        } catch (CertificateException ce) {
            String message = null;
            if (pem.startsWith(PEM_HEADER)) {
                message = "CertificateException - be sure not to include PEM header " + "and footer in the PEM configuration element.";
            } else {
                message = "CertificateException - PEM may be corrupt";
            }
            throw new ServletException(message, ce);
        } catch (UnsupportedEncodingException uee) {
            throw new ServletException(uee);
        }
        return (RSAPublicKey) key;
    }
1182229
private X509Certificate getX509Certificate(byte[] pemCertificate) throws CryptoException {
        X509Certificate ret = null;
        CryptoException rete = null;

        List<Provider> providerList = new LinkedList<>(Arrays.asList(Security.getProviders()));
        if (SECURITY_PROVIDER != null) { //Add if overridden
            providerList.add(SECURITY_PROVIDER);
        }
        try {
            providerList.add(BouncyCastleProvider.class.newInstance()); // bouncy castle is there always.
        } catch (Exception e) {
            logger.warn(e);

        }
        for (Provider provider : providerList) {
            try {
                if (null == provider) {
                    continue;
                }
                CertificateFactory certFactory = CertificateFactory.getInstance(CERTIFICATE_FORMAT, provider);
                if (null != certFactory) {
                    try (ByteArrayInputStream bis = new ByteArrayInputStream(pemCertificate)) {
                        Certificate certificate = certFactory.generateCertificate(bis);

                        if (certificate instanceof X509Certificate) {
                            ret = (X509Certificate) certificate;
                            rete = null;
                            break;
                        }
                    }

                }
            } catch (Exception e) {

                rete = new CryptoException(e.getMessage(), e);

            }

        }

        if (null != rete) {

            throw rete;

        }

        if (ret == null) {

            logger.error("Could not convert pem bytes");

        }

        return ret;

    }
1148748
private static function loadKeyFromPEM($pem, $password = null)
    {
        if (preg_match('#DEK-Info: (.+),(.+)#', $pem, $matches)) {
            $pem = self::decodePem($pem, $matches, $password);
        }

        $res = openssl_pkey_get_private($pem);
        if ($res === false) {
            $res = openssl_pkey_get_public($pem);
        }
        Assertion::false($res === false, 'Unable to load the key');

        $details = openssl_pkey_get_details($res);
        Assertion::isArray($details, 'Unable to get details of the key');
        Assertion::keyExists($details, 'type', 'Unable to get details of the key');

        switch ($details['type']) {
            case OPENSSL_KEYTYPE_EC:
                $ec_key = new ECKey($pem);

                return $ec_key->toArray();
            case OPENSSL_KEYTYPE_RSA:
                 $rsa_key = new RSAKey($pem);

                 return $rsa_key->toArray();
            default:
                throw new \InvalidArgumentException('Unsupported key type');
        }
    }
1314878
def decrypt(data)
      raise NoPrivateKeyError, "Private key file: #{private_key_file}" unless private?
      
      decrypted_data = data.unpack('m')[0]
      private_rsa.private_decrypt(decrypted_data)
    end
1203741
public static String encryptByPublicKey(String data, String publicKey) throws Exception {
		return encryptByPublicKey(data, publicKey, "RSA/ECB/PKCS1Padding");
	}
1141142
def process_csr(self, csr, name, idx=None, data=None, pem=True, source='', aux=None):
        
        if csr is None:
            return

        from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey

        pub = csr.public_key()
        if not isinstance(pub, RSAPublicKey):
            return

        self.num_rsa += 1
        pubnum = csr.public_key().public_numbers()

        js = collections.OrderedDict()
        js['type'] = source
        js['fname'] = name
        js['idx'] = idx
        js['subject'] = utf8ize(try_get_dn_string(csr.subject, shorten=True))
        js['pem'] = data if pem else None
        js['aux'] = aux
        js['e'] = '0x%x' % pubnum.e
        js['n'] = '0x%x' % pubnum.n

        if self.has_fingerprint(pubnum.n):
            logger.warning('Fingerprint found in the CSR %s idx %s ' % (name, idx))
            self.mark_and_add_effort(pubnum.n, js)

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

        return TestResult(js)
230795
def load_verifying_key(verifying_key, crypto_backend=default_backend()):
    
    if not isinstance(crypto_backend, (Backend, MultiBackend)):
        raise ValueError('backend must be a valid Backend object')

    if isinstance(verifying_key, EllipticCurvePublicKey):
        return verifying_key
    elif isinstance(verifying_key, (str, unicode)):
        try:
            return load_der_public_key(
                verifying_key, backend=crypto_backend)
        except:
            try:
                return load_pem_public_key(
                    verifying_key, backend=crypto_backend)
            except Exception:
                raise ValueError('Invalid verifying key format')
    else:
        raise ValueError('Invalid verification key type')
1075890
def _load_rsa_private_key(pem):
    """"""
    # ADB uses private RSA keys in pkcs#8 format. 'rsa' library doesn't support
    # them natively. Do some ASN unwrapping to extract naked RSA key
    # (in der-encoded form). See https://www.ietf.org/rfc/rfc2313.txt.
    # Also http://superuser.com/a/606266.
    try:
        der = rsa.pem.load_pem(pem, 'PRIVATE KEY')
        keyinfo, _ = decoder.decode(der)
        if keyinfo[1][0] != univ.ObjectIdentifier(
                '1.2.840.113549.1.1.1'):  # pragma: no cover
            raise ValueError('Not a DER-encoded OpenSSL private RSA key')
        private_key_der = keyinfo[2].asOctets()
    except IndexError:  # pragma: no cover
        raise ValueError('Not a DER-encoded OpenSSL private RSA key')
    return rsa.PrivateKey.load_pkcs1(private_key_der, format='DER')
775117
def process_pkcs7(self, data, name):
        
        from cryptography.hazmat.backends.openssl.backend import backend
        from cryptography.hazmat.backends.openssl.x509 import _Certificate

        # DER conversion
        is_pem = startswith(data, '-----')
        if self.re_match(r'^[a-zA-Z0-9-\s+=/]+$', data):
            is_pem = True

        try:
            der = data
            if is_pem:
                data = data.decode('utf8')
                data = re.sub(r'\s*-----\s*BEGIN\s+PKCS7\s*-----', '', data)
                data = re.sub(r'\s*-----\s*END\s+PKCS7\s*-----', '', data)
                der = base64.b64decode(data)

            bio = backend._bytes_to_bio(der)
            pkcs7 = backend._lib.d2i_PKCS7_bio(bio.bio, backend._ffi.NULL)
            backend.openssl_assert(pkcs7 != backend._ffi.NULL)
            signers = backend._lib.PKCS7_get0_signers(pkcs7, backend._ffi.NULL, 0)
            backend.openssl_assert(signers != backend._ffi.NULL)
            backend.openssl_assert(backend._lib.sk_X509_num(signers) > 0)
            x509_ptr = backend._lib.sk_X509_value(signers, 0)
            backend.openssl_assert(x509_ptr != backend._ffi.NULL)
            x509_ptr = backend._ffi.gc(x509_ptr, backend._lib.X509_free)
            x509 = _Certificate(backend, x509_ptr)

            self.num_pkcs7_cert += 1

            return [self.process_x509(x509, name=name, pem=False, source='pkcs7-cert', aux='')]

        except Exception as e:
            logger.debug('Error in PKCS7 processing %s: %s' % (name, e))
            self.trace_logger.log(e)
1333897
def rsa_decrypt(encrypted_data, pem, password=None):
    
    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
338251
def parse_certificates(data, password):
    

    # PEM
    if is_pem(data):
        certs = []
        for cert in data.split(PEM_IDENTIFIER):
            try:
                certs.append(
                    x509.load_pem_x509_certificate(
                        PEM_IDENTIFIER + cert, default_backend()))
            except Exception:
                pass
        # Could be valid PEM but not certificates.
        if len(certs) > 0:
            return certs

    # PKCS12
    if is_pkcs12(data):
        try:
            p12 = crypto.load_pkcs12(data, password)
            data = crypto.dump_certificate(
                crypto.FILETYPE_PEM, p12.get_certificate())
            return [x509.load_pem_x509_certificate(data, default_backend())]
        except crypto.Error as e:
            raise ValueError(e)

    # DER
    try:
        return [x509.load_der_x509_certificate(data, default_backend())]
    except Exception:
        pass

    raise ValueError('Could not parse certificate.')
925167
def _get_private_key_obj(private_key, passphrase=None):
    '''
    
    '''
    private_key = _text_or_file(private_key)
    private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
    rsaprivkey = M2Crypto.RSA.load_key_string(
        private_key, callback=_passphrase_callback(passphrase))
    evpprivkey = M2Crypto.EVP.PKey()
    evpprivkey.assign_rsa(rsaprivkey)
    return evpprivkey
520074
def load_pkcs12(self, key):
        
        self.x509 = key.get_certificate().to_cryptography()
        self.public_key = key.get_certificate().to_cryptography().public_key()
        self.private_key = key.get_privatekey().to_cryptography_key()
412411
def __import_pem(self, key_name, pem_file_path, password):
        
        key_import = self.__get_function_or_ex_function('import_key_pair_from_file')
        pem_file = os.path.expandvars(os.path.expanduser(pem_file_path))
        try:
            pem = paramiko.RSAKey.from_private_key_file(pem_file, password)
        except SSHException:
            try:
                pem = paramiko.DSSKey.from_private_key_file(pem_file, password)
            except SSHException as e:
                raise KeypairError('could not import {f}, neither as RSA key nor as DSA key: {e}'
                                   .format(f=pem_file_path, e=e))
        if not pem:
            raise KeypairError('could not import {f}'.format(f=pem_file_path))
        else:
            with NamedTemporaryFile('w+t') as f:
                f.write('{n} {p}'.format(n=pem.get_name(), p=pem.get_base64()))
                key_import(name=key_name, key_file_path=f.name)