Parse and validate the certificate and private key, also extracts usefull data and sets it on this object
Also throws exceptions if the certificate/private key doesn't seem to be a valid APNS cert
181404
private function parseCertificate()
	{
		$now = new \DateTime();

		// Parse the certificate
		$certificateData = openssl_x509_parse( file_get_contents($this->getPemFile()) );
		if (false == $certificateData) {
			throw new InvalidCertificateException('Unable to parse certificate "' . $this->getPemFile() . '", are you sure this is a valid PEM certificate?');
		}

		// Validate the "valid from" timestamp
		if (isset($certificateData['validFrom_time_t']))
		{
			$validFrom = new \DateTime('@' . $certificateData['validFrom_time_t']);
			if ($validFrom > $now) {
				throw new InvalidCertificateException('Certificate "' . $this->getPemFile() . '" not yet valid, valid from ' . $validFrom->format(\DateTime::ISO8601) . '.');
			}

			$this->validFrom = $validFrom;
		}
		else {
			throw new InvalidCertificateException('Certificate "' . $this->getPemFile() . '" has no valid from timestamp.');
		}

		// Validate the "valid to" timestamp
		if (isset($certificateData['validTo_time_t']))
		{
			$validTo = new \DateTime('@' . $certificateData['validTo_time_t']);
			if ($validTo < $now)
			{
				throw new InvalidCertificateException('Certificate "' . $this->getPemFile() . '" expired, was valid until ' . $validTo->format(\DateTime::ISO8601) . '.');
			}

			$this->validTo = $validTo;
		}
		else {
			throw new InvalidCertificateException('Certificate "' . $this->getPemFile() . '" has no valid to timestamp.');
		}

		// Check if the certificate was issued by Apple
		if (!isset($certificateData['issuer']) || !isset($certificateData['issuer']['O']) || 'Apple Inc.' != $certificateData['issuer']['O']) {
			throw new InvalidCertificateException('Certificate "' . $this->getPemFile() . '" does not list Apple Inc. as the issuer.');
		}

		// Check if the there is an environment hidden in the certificate
		if (isset($certificateData['subject']) && isset($certificateData['subject']['CN']))
		{
			$this->description = $certificateData['subject']['CN'];

			if (null === $this->endpointEnv)
			{
				if (strpos($certificateData['subject']['CN'], 'Pass Type ID') === 0 ||
					strpos($certificateData['subject']['CN'], 'Apple Push Services') === 0 ||
					strpos($certificateData['subject']['CN'], 'Apple Production IOS Push Services') === 0 ||
					strpos($certificateData['subject']['CN'], 'Apple Production Mac Push Services') === 0) {
					// Passbook Pass certificate & APNS Production/hybrid certs, should be on production
					$this->endpointEnv = self::ENDPOINT_ENV_PRODUCTION;
				} else if (	strpos($certificateData['subject']['CN'], 'Apple Development IOS Push Services') === 0 ||
							strpos($certificateData['subject']['CN'], 'Apple Development Mac Push Services') === 0) {
					// APNS Development, should always be on sandbox
					$this->endpointEnv = self::ENDPOINT_ENV_SANDBOX;
				} else {
					throw new InvalidCertificateException('Could not detect APNS environment based on the CN string "' . $certificateData['subject']['CN'] . '" in certificate "' . $this->getPemFile() . '".');
				}
			}
		}
		else
		{
			throw new InvalidCertificateException('No APNS environment information found in certificate "' . $this->getPemFile() . '".');
		}

		// Validate the private key by loading it
		$privateKey = openssl_pkey_get_private('file://' . $this->getPemFile(), $this->getPassphrase() );
		if (false === $privateKey) {
			throw new InvalidCertificateException('Could not extract the private key from certificate "' . $this->getPemFile() . '", please check if the given passphrase is correct and if it contains a private key.');
		}

		// If a passphrase is given, the private key may not be loaded without it
		if ($this->getPassphrase() != null)
		{
			// Try to load the private key without the passphrase (should fail)
			$privateKey = openssl_pkey_get_private('file://' . $this->getPemFile() );
			if (false !== $privateKey) {
				throw new InvalidCertificateException('Passphrase given, but the private key in "' . $this->getPemFile() . '" is not encrypted, please make sure you are using the correct certificate/passphrase combination.');
			}
		}
	}
541108
def get_ssl_context(private_key, certificate):
    
    if (
        certificate
        and os.path.isfile(certificate)
        and private_key
        and os.path.isfile(private_key)
    ):
        context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
        context.load_cert_chain(certificate, private_key)
        return context
    return None
1301534
function (cert, cb) {
    var infoObject = {},
        subjectElements = [],
        err;

  	var openssl = spawn('openssl', ['req', '-noout', '-subject', '-nameopt', 'RFC2253']);

    // Catch stderr
    openssl.stderr.on('data', function (out) {
      err = new Error(out);

      // Callback and return array
  		return cb(err, infoObject);
    });

    openssl.stdout.on('data', function (out) {
      var data = out.toString();

      // Put each line into an array
      var lineArray = data.split('\n');

      // Filter out empty ones
      lineArray = lineArray.filter(function(n){ return n !== undefined && n !== '' });

      /* Construct infoObject */

      // Certificate
      infoObject.certificate = cert;

      // Subject
      infoObject.subject = {};
      // Split by "/" prefix
      subjectElements = lineArray[0].replace('subject=', '').split(',');
      // For each elements
      for (var iS = 0; iS < subjectElements.length; iS++) {
        // Split keys and values by "=" separator
        var subjectKeyValue = subjectElements[iS].split('=');
        infoObject.subject[subjectKeyValue[0]] = subjectKeyValue[1];
      }

      // Callback and return array
  		return cb(err, infoObject);
  	});

  	openssl.stdin.write(cert);
  	openssl.stdin.end();
  }
156778
public function parse(Certificate $certificate)
    {
        $rawData = openssl_x509_parse($certificate->getPEM());

        if (!\is_array($rawData)) {
            throw new CertificateParsingException(
                sprintf('Fail to parse certificate with error: %s', openssl_error_string())
            );
        }

        if (!isset($rawData['subject']['CN'])) {
            throw new CertificateParsingException('Missing expected key "subject.cn" in certificate');
        }
        if (!isset($rawData['serialNumber'])) {
            throw new CertificateParsingException('Missing expected key "serialNumber" in certificate');
        }
        if (!isset($rawData['validFrom_time_t'])) {
            throw new CertificateParsingException('Missing expected key "validFrom_time_t" in certificate');
        }
        if (!isset($rawData['validTo_time_t'])) {
            throw new CertificateParsingException('Missing expected key "validTo_time_t" in certificate');
        }

        $subjectAlternativeName = [];

        if (isset($rawData['extensions']['subjectAltName'])) {
            $subjectAlternativeName = array_map(
                function ($item) {
                    return explode(':', trim($item), 2)[1];
                },
                array_filter(
                    explode(
                        ',',
                        $rawData['extensions']['subjectAltName']
                    ),
                    function ($item) {
                        return false !== strpos($item, ':');
                    }
                )
            );
        }

        return new ParsedCertificate(
            $certificate,
            $rawData['subject']['CN'],
            isset($rawData['issuer']['CN']) ? $rawData['issuer']['CN'] : null,
            $rawData['subject'] === $rawData['issuer'],
            new \DateTime('@'.$rawData['validFrom_time_t']),
            new \DateTime('@'.$rawData['validTo_time_t']),
            $rawData['serialNumber'],
            $subjectAlternativeName
        );
    }
736759
def active_cert(key):
    
    try:
        cert_str = pem_format(key)
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_str)
        assert cert.has_expired() == 0
        assert not OpenSSLWrapper().certificate_not_valid_yet(cert)
        return True
    except AssertionError:
        return False
    except AttributeError:
        return False
659739
def enable_cert_auth(public_key = '~/.ssh/id_rsa.pub')
      cert_regex = /^ssh-[rd]sa (?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)? \S*$/m

      # get our cert unless the user provided a full cert for us.
      unless public_key =~ cert_regex
        public_key = File.expand_path(public_key)
        if File.exist?(public_key)
          public_key = File.read(public_key).to_s.strip
        else
          raise Shells::PfSenseCommon::PublicKeyNotFound
        end
        raise Shells::PfSenseCommon::PublicKeyInvalid unless public_key =~ cert_regex
      end

      cfg = get_config_section 'system'
      user_id = nil
      user_name = options[:user].downcase
      cfg['user'].each_with_index do |user,index|
        if user['name'].downcase == user_name
          user_id = index

          authkeys = Base64.decode64(user['authorizedkeys'].to_s).gsub("\r\n", "\n").strip
          unless authkeys == '' || authkeys =~ cert_regex
            warn "Existing authorized keys for user #{options[:user]} are invalid and are being reset."
            authkeys = ''
          end

          if authkeys == ''
            user['authorizedkeys'] = Base64.strict_encode64(public_key)
          else
            authkeys = authkeys.split("\n")
            unless authkeys.include?(public_key)
              authkeys << public_key unless authkeys.include?(public_key)
              user['authorizedkeys'] = Base64.strict_encode64(authkeys.join("\n"))
            end
          end

          break
        end
      end


      raise Shells::PfSenseCommon::UserNotFound unless user_id

      set_config_section 'system', cfg, "Enable certificate authentication for #{options[:user]}."

      apply_user_config user_id
    end
751136
def cert_pair(self):
        
        if self._ssl_cert and self._ssl_private_key:
            return (self._ssl_cert, self._ssl_private_key)
        else:
            return None
709497
def parse_client_cert_pair(config_value):
    
    if not config_value:
        return
    client_cert = config_value.split(':')
    if len(client_cert) != 2:
        tips = ('client_cert should be formatted like '
                '"/path/to/cert.pem:/path/to/key.pem"')
        raise ValueError('{0!r} is invalid.\n{1}'.format(config_value, tips))
    return tuple(client_cert)
934252
def load_pem(cls, private_key, password=None):
        
        # TODO(sam): try to break this in tests
        maybe_path = normpath(private_key)
        if os.path.isfile(maybe_path):
            with open(maybe_path, 'rb') as pkf:
                private_key = pkf.read()
        if not isinstance(private_key, six.binary_type):
            private_key = private_key.encode('utf-8')

        pkey = serialization.load_pem_private_key(
            private_key,
            password=password,
            backend=crypto_backends.default_backend())
        return cls(pkey)
291410
def Verify(self, public_key):
    
    # TODO(amoser): We have to do this manually for now since cryptography does
    # not yet support cert verification. There is PR 2460:
    # https://github.com/pyca/cryptography/pull/2460/files
    # that will add it, once it's in we should switch to using this.

    # Note that all times here are in UTC.
    now = rdfvalue.RDFDatetime.Now().AsDatetime()
    if now > self._value.not_valid_after:
      raise VerificationError("Certificate expired!")
    if now < self._value.not_valid_before:
      raise VerificationError("Certificate not yet valid!")

    public_key.Verify(
        self._value.tbs_certificate_bytes,
        self._value.signature,
        hash_algorithm=self._value.signature_hash_algorithm)
    return True
1137616
def _validate_and_parse_block_key(self, block_key, course_key_obj):
        
        try:
            block_key_obj = UsageKey.from_string(block_key)
        except InvalidKeyError:
            raise ValidationError(_("Invalid block key: {}").format(block_key))

        if block_key_obj.run is None:
            expected_matching_course_key = course_key_obj.replace(run=None)
        else:
            expected_matching_course_key = course_key_obj

        if block_key_obj.course_key != expected_matching_course_key:
            raise ValidationError(
                _("Block with key: '{key}' is not in course {course}").format(key=block_key, course=course_key_obj)
            )

        return block_key_obj
1231415
private function parseSSL()
    {
        if($this->request->getAttribute('isVerifyCA', false))
        {
            curl_setopt_array($this->handler, array(
                CURLOPT_SSL_VERIFYPEER    => true,
                CURLOPT_CAINFO            => $this->request->getAttribute('caCert'),
                CURLOPT_SSL_VERIFYHOST    => 2,
            ));
        }
        else
        {
            curl_setopt_array($this->handler, array(
                CURLOPT_SSL_VERIFYPEER    => false,
                CURLOPT_SSL_VERIFYHOST    => 0,
            ));
        }
        $certPath = $this->request->getAttribute('certPath', '');
        if('' !== $certPath)
        {
            curl_setopt_array($this->handler, array(
                CURLOPT_SSLCERT         => $certPath,
                CURLOPT_SSLCERTPASSWD   => $this->request->getAttribute('certPassword'),
                CURLOPT_SSLCERTTYPE     => $this->request->getAttribute('certType', 'pem'),
            ));
        }
        $keyPath = $this->request->getAttribute('keyPath', '');
        if('' !== $keyPath)
        {
            curl_setopt_array($this->handler, array(
                CURLOPT_SSLKEY          => $keyPath,
                CURLOPT_SSLKEYPASSWD    => $this->request->getAttribute('keyPassword'),
                CURLOPT_SSLKEYTYPE      => $this->request->getAttribute('keyType', 'pem'),
            ));
        }
    }
903673
def _parse_ocsp_response_from_openssl_text(
            cls,
            response_text: str,
            response_status: OcspResponseStatusEnum
    ) -> Dict[str, Any]:
        
        response_dict = {
            'responseStatus': cls._get_value_from_text_output_no_p('OCSP Response Status:', response_text),
            'version': cls._get_value_from_text_output_no_p('Version:', response_text),
            'responseType': cls._get_value_from_text_output('Response Type:', response_text),
            'responderID': cls._get_value_from_text_output('Responder Id:', response_text),
            'producedAt': cls._get_value_from_text_output('Produced At:', response_text),
            }  # type: Dict[str, Any]

        if response_status != OcspResponseStatusEnum.SUCCESSFUL:
            return response_dict

        # A successful OCSP response will contain more data - let's parse it
        # TODO(ad): This will not work correctly if there are multiple responses as it assumes just one
        response_dict['responses'] = [
            {
                'certID': {
                    'hashAlgorithm': cls._get_value_from_text_output('Hash Algorithm:', response_text),
                    'issuerNameHash': cls._get_value_from_text_output('Issuer Name Hash:', response_text),
                    'issuerKeyHash': cls._get_value_from_text_output('Issuer Key Hash:', response_text),
                    'serialNumber': cls._get_value_from_text_output('Serial Number:', response_text)
                },
                'certStatus': cls._get_value_from_text_output('Cert Status:', response_text),
                'thisUpdate': cls._get_value_from_text_output('This Update:', response_text),
                'nextUpdate': cls._get_value_from_text_output('Next Update:', response_text),
            }
        ]
        if cls._get_scts_from_text_output(response_text):
            # SCT extension present
            response_dict['responses'][0]['singleExtensions'] = {
                'ctCertificateScts': cls._get_scts_from_text_output(response_text)
            }
        return response_dict
64594
private void parseSSLCertFile() {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "parseSSLCertFile");
        }

        String fileName = null;
        String lineRead = null;
        BufferedReader bufferReader = null;

        // Obtain Default Cert Label
        certDefaultLabel = getProperty(PROTOCOL_HTTPS_CERT_DEFAULT_LABEL);

        // Obtain Cert Mapping File
        try {
            fileName = getProperty(PROTOCOL_HTTPS_CERT_MAPPING_FILE);

            if (fileName != null && 0 < fileName.length()) {
                bufferReader = new BufferedReader(new FileReader(fileName));

                // For each entry, parse the label and ip address
                lineRead = bufferReader.readLine();
                while (lineRead != null) {
                    extractSSLServerCert(lineRead.trim());
                    lineRead = bufferReader.readLine();
                }
            }
        } catch (Exception e) {
            FFDCFilter.processException(e, getClass().getName(), "parseSSLCertFile", this);
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "Error parsing file; " + e);
        } finally {
            if (null != bufferReader) {
                try {
                    bufferReader.close();
                } catch (IOException ioe) {
                    // ignore
                }
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "parseSSLCertFile");
        }
    }
552005
def parse_v3_signing_block(self):
        

        self._v3_signing_data = []

        # calling is_signed_v3 should also load the signature, if any
        if not self.is_signed_v3():
            return

        block_bytes = self._v2_blocks[self._APK_SIG_KEY_V3_SIGNATURE]
        block = io.BytesIO(block_bytes)
        view = block.getvalue()

        # V3 signature Block data format:
        #
        # * signer:
        #    * signed data:
        #        * digests:
        #            * signature algorithm ID (uint32)
        #            * digest (length-prefixed) 
        #        * certificates
        #        * minSDK
        #        * maxSDK
        #        * additional attributes
        #    * minSDK
        #    * maxSDK
        #    * signatures
        #    * publickey
        size_sequence = self.read_uint32_le(block)
        if size_sequence + 4 != len(block_bytes):
            raise BrokenAPKError("size of sequence and blocksize does not match")

        while block.tell() < len(block_bytes):
            off_signer = block.tell()
            size_signer = self.read_uint32_le(block)

            # read whole signed data, since we might to parse
            # content within the signed data, and mess up offset
            len_signed_data = self.read_uint32_le(block)
            signed_data_bytes = block.read(len_signed_data)
            signed_data = io.BytesIO(signed_data_bytes)

            # Digests
            len_digests = self.read_uint32_le(signed_data)
            raw_digests = signed_data.read(len_digests)
            digests = self.parse_signatures_or_digests(raw_digests)


            # Certs
            certs = []
            len_certs = self.read_uint32_le(signed_data)
            start_certs = signed_data.tell()
            while signed_data.tell() < start_certs + len_certs:

                len_cert = self.read_uint32_le(signed_data)
                cert = signed_data.read(len_cert)
                certs.append(cert)

            # versions
            signed_data_min_sdk = self.read_uint32_le(signed_data)
            signed_data_max_sdk = self.read_uint32_le(signed_data)

            # Addional attributes
            len_attr = self.read_uint32_le(signed_data)
            attr = signed_data.read(len_attr)

            signed_data_object = APKV3SignedData()
            signed_data_object._bytes = signed_data_bytes
            signed_data_object.digests = digests
            signed_data_object.certificates = certs
            signed_data_object.additional_attributes = attr
            signed_data_object.minSDK = signed_data_min_sdk
            signed_data_object.maxSDK = signed_data_max_sdk

            # versions (should be the same as signed data's versions)
            signer_min_sdk = self.read_uint32_le(block)
            signer_max_sdk = self.read_uint32_le(block)

            # Signatures
            len_sigs = self.read_uint32_le(block)
            raw_sigs = block.read(len_sigs)
            sigs = self.parse_signatures_or_digests(raw_sigs)

            # PublicKey
            len_publickey = self.read_uint32_le(block)
            publickey = block.read(len_publickey)

            signer = APKV3Signer()
            signer._bytes = view[off_signer:off_signer+size_signer]
            signer.signed_data = signed_data_object
            signer.signatures = sigs
            signer.public_key = publickey
            signer.minSDK = signer_min_sdk
            signer.maxSDK = signer_max_sdk

            self._v3_signing_data.append(signer)
516047
def get_key
      # check for a private key string
      if encoded_key = Gxapi.config.google.respond_to?(:private_key)
        OpenSSL::PKey::RSA.new(
          Base64.decode64(Gxapi.config.google.private_key),
          'notasecret'
        )
      else
        Google::APIClient::KeyUtils.load_from_pkcs12(
          Gxapi.config.google.private_key_path,
          'notasecret'
        )
      end
    end
504480
public void validate(KeyStore keyStore, Certificate cert) throws CertificateException
{
    Certificate[] certChain = null;
    
    if (cert != null && cert instanceof X509Certificate)
    {
        ((X509Certificate)cert).checkValidity();
        
        String certAlias = null;
        try
        {
            if (keyStore == null)
            {
                throw new InvalidParameterException("Keystore cannot be null");
            }

            certAlias = keyStore.getCertificateAlias((X509Certificate)cert);
            if (certAlias == null)
            {
                certAlias = "JETTY" + String.format("%016X",__aliasCount.incrementAndGet());
                keyStore.setCertificateEntry(certAlias, cert);
            }
            
            certChain = keyStore.getCertificateChain(certAlias);
            if (certChain == null || certChain.length == 0)
            {
                throw new IllegalStateException("Unable to retrieve certificate chain");
            }
        }
        catch (KeyStoreException kse)
        {
            LOG.error("Error while valid keystore", kse);
            throw new CertificateException("Unable to validate certificate" +
                    (certAlias == null ? "":" for alias [" +certAlias + "]") + ": " + kse.getMessage(), kse);
        }
        
        validate(certChain);
    } 
}