Create and return a Certification document

    :param current_block: Current block data
    :param self_cert_document: Identity document
    :param from_pubkey: Pubkey of the certifier

    :rtype: Certification
345847
def get_certification_document(current_block: dict, self_cert_document: Identity, from_pubkey: str) -> Certification:
    
    # construct Certification Document
    return Certification(version=10, currency=current_block['currency'], pubkey_from=from_pubkey,
                                  identity=self_cert_document,
                                  timestamp=BlockUID(current_block['number'], current_block['hash']), signature="")
1301455
def certs(self, entity_id, descriptor, use="signing"):
        '''
        
        '''
        ent = self[entity_id]

        def extract_certs(srvs):
            res = []
            for srv in srvs:
                if "key_descriptor" in srv:
                    for key in srv["key_descriptor"]:
                        if "use" in key and key["use"] == use:
                            for dat in key["key_info"]["x509_data"]:
                                cert = repack_cert(
                                    dat["x509_certificate"]["text"])
                                if cert not in res:
                                    res.append(cert)
                        elif not "use" in key:
                            for dat in key["key_info"]["x509_data"]:
                                cert = repack_cert(
                                    dat["x509_certificate"]["text"])
                                if cert not in res:
                                    res.append(cert)

            return res

        if descriptor == "any":
            res = []
            for descr in ["spsso", "idpsso", "role", "authn_authority",
                          "attribute_authority", "pdp"]:
                try:
                    srvs = ent["%s_descriptor" % descr]
                except KeyError:
                    continue

                res.extend(extract_certs(srvs))
        else:
            srvs = ent["%s_descriptor" % descriptor]
            res = extract_certs(srvs)

        return res
1002202
def get_public_key_pem(cert_obj):
    
    return cert_obj.public_key().public_bytes(
        encoding=cryptography.hazmat.primitives.serialization.Encoding.PEM,
        format=cryptography.hazmat.primitives.serialization.PublicFormat.PKCS1,
    )
202096
def get(self, bits=2048, type=crypto.TYPE_RSA, digest='sha1'):
        
        self.log.debug('Creating a new self-signed SSL certificate')
        # Generate the key and ready our cert
        key = crypto.PKey()
        key.generate_key(type, bits)
        cert = crypto.X509()

        # Fill in some pseudo certificate information with a wildcard common name
        cert.get_subject().C  = 'US'
        cert.get_subject().ST = 'California'
        cert.get_subject().L  = 'Los Angeles'
        cert.get_subject().O  = 'Wright Anything Agency'
        cert.get_subject().OU = 'Law firm / talent agency'
        cert.get_subject().CN = '*.{dn}'.format(dn=self.site.domain.name)

        # Set the serial number, expiration and issued
        cert.set_serial_number(1000)
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(315360000)
        cert.set_issuer(cert.get_subject())

        # Map the key and sign our certificate
        cert.set_pubkey(key)
        cert.sign(key, digest)

        # Dump the PEM data and return a certificate container
        _cert = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
        _key  = crypto.dump_privatekey(crypto.FILETYPE_PEM, key)

        return Certificate(_cert, _key, type, bits, digest)
780417
def create_self_signed_cert():
    """"""
    config_dir = Path(BaseDirectory.xdg_config_home) / 'xenon-grpc'
    config_dir.mkdir(parents=True, exist_ok=True)

    key_prefix = gethostname()
    crt_file = config_dir / ('%s.crt' % key_prefix)
    key_file = config_dir / ('%s.key' % key_prefix)

    if crt_file.exists() and key_file.exists():
        return crt_file, key_file

    logger = logging.getLogger('xenon')
    logger.info("Creating authentication keys for xenon-grpc.")

    # create a key pair
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, 1024)

    # create a self-signed cert
    cert = crypto.X509()
    cert.get_subject().CN = gethostname()
    cert.set_serial_number(1000)
    cert.gmtime_adj_notBefore(0)
    # valid for almost ten years!
    cert.gmtime_adj_notAfter(10 * 365 * 24 * 3600)
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(k)
    cert.sign(k, 'sha256')

    open(str(crt_file), "wb").write(
        crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    open(str(key_file), "wb").write(
        crypto.dump_privatekey(crypto.FILETYPE_PEM, k))

    return crt_file, key_file
834226
def sign_certificate():
    
    LOGGER.info("Signing certificate...")
    cmd = [
        'openssl', 'req',
        '-in', os.path.join(gettempdir(), 'domain.csr'),
        '-outform', 'DER'
    ]
    devnull = open(os.devnull, 'wb')
    csr_der = subprocess.check_output(cmd, stderr=devnull)
    code, result = _send_signed_request(DEFAULT_CA + "/acme/new-cert", {
        "resource": "new-cert",
        "csr": _b64(csr_der),
    })
    if code != 201:
        raise ValueError("Error signing certificate: {0} {1}".format(code, result))
    LOGGER.info("Certificate signed!")

    return result
687467
def serialize_cert_to_pem(cert_obj):
    
    return cert_obj.public_bytes(
        encoding=cryptography.hazmat.primitives.serialization.Encoding.PEM
    )
1089204
def build_cert_chain(self, flags=SSL_BUILD_CHAIN_FLAG_NONE):
        
        '''
        retVal = SSL_CTX_build_cert_chain(self._ctx, flags)
        return retVal
148482
def from_signed_raw(cls: Type[MembershipType], signed_raw: str) -> MembershipType:
        
        lines = signed_raw.splitlines(True)
        n = 0

        version = int(Membership.parse_field("Version", lines[n]))
        n += 1

        Membership.parse_field("Type", lines[n])
        n += 1

        currency = Membership.parse_field("Currency", lines[n])
        n += 1

        issuer = Membership.parse_field("Issuer", lines[n])
        n += 1

        membership_ts = BlockUID.from_str(Membership.parse_field("Block", lines[n]))
        n += 1

        membership_type = Membership.parse_field("Membership", lines[n])
        n += 1

        uid = Membership.parse_field("UserID", lines[n])
        n += 1

        identity_ts = BlockUID.from_str(Membership.parse_field("CertTS", lines[n]))
        n += 1

        signature = Membership.parse_field("Signature", lines[n])
        n += 1

        return cls(version, currency, issuer, membership_ts,
                   membership_type, uid, identity_ts, signature)
654451
async def certify(client: Client, certification_signed_raw: str) -> ClientResponse:
    
    return await client.post(MODULE + '/certify', {'cert': certification_signed_raw}, rtype=RESPONSE_AIOHTTP)
893754
def prepare_batch(self):
        
        
        for cert in self.certificates_to_issue:
            self.certificate_handler.validate_certificate(cert)

        self.merkle_tree.populate(self.get_certificate_generator())
        logging.info('here is the op_return_code data: %s', b2h(self.merkle_tree.get_blockchain_data()))
        return self.merkle_tree.get_blockchain_data()
279311
public GlobusCredential createCredential(X509Certificate[] certs, PrivateKey privateKey, int bits, int lifetime,
        int delegationMode) throws GeneralSecurityException {
        return createCredential(certs, privateKey, bits, lifetime, delegationMode, (X509ExtensionSet) null, null);
    }
659086
def get_certificate_generator(self):
        

        for cert in self.certificates_to_issue:
            data_to_issue = self.certificate_handler.get_byte_array_to_issue(cert)
            yield data_to_issue
1359798
def raw(self) -> str:
        
        if not isinstance(self.identity, Identity):
            raise MalformedDocumentError("Can not return full revocation document created from inline")

        return """Version: {version}
Type: Revocation
Currency: {currency}
Issuer: {pubkey}
IdtyUniqueID: {uid}
IdtyTimestamp: {timestamp}
IdtySignature: {signature}
""".format(version=self.version,
           currency=self.currency,
           pubkey=self.identity.pubkey,
           uid=self.identity.uid,
           timestamp=self.identity.timestamp,
           signature=self.identity.signatures[0])
1074176
def generate_certificate_pure_python(common_name, size=DEFAULT_KEY_SIZE,
                                        digest=DEFAULT_DIGEST):
    '''
        
    '''
    private_key = OpenSSL.crypto.PKey()
    private_key.generate_key(TYPE_RSA, size)

    request = OpenSSL.crypto.X509Req()
    subject = request.get_subject()
    setattr(subject, 'CN', common_name)
    request.set_pubkey(private_key)
    request.sign(private_key, digest)

    certificate = OpenSSL.crypto.X509()
    certificate.set_serial_number(0)
    certificate.gmtime_adj_notBefore(0)
    certificate.gmtime_adj_notAfter(60 * 60 * 24 * 365 * 5)
    certificate.set_issuer(request.get_subject())
    certificate.set_subject(request.get_subject())
    certificate.set_pubkey(request.get_pubkey())
    certificate.sign(private_key, digest)

    private_key_path = '{}/{}.key'.format(CERTIFICATES_PATH, common_name)
    if not os.path.isfile(private_key_path):
        print 'Write {}'.format(private_key_path)
        with open(private_key_path, 'w+') as private_key_file:
            private_key_file.write(
                OpenSSL.crypto.dump_privatekey(FILETYPE_PEM,
                                               private_key).decode('utf-8')
            )
        helpers.file_rights(private_key_path, mode=0400, uid=0, gid=0)
    else:
        print 'Already exist: {}'.format(private_key_path)

    certificate_path = '{}/{}.crt'.format(CERTIFICATES_PATH, common_name)
    if not os.path.isfile(certificate_path):
        print 'Write {}'.format(certificate_path)
        with open(certificate_path, 'w+') as certificate_file:
            certificate_file.write(
                OpenSSL.crypto.dump_certificate(FILETYPE_PEM,
                                                certificate).decode('utf-8')
            )
        helpers.file_rights(certificate_path, mode=0444, uid=0, gid=0)
    else:
        print 'Already exist: {}'.format(certificate_path)

    clean_links()
    make_links(common_name)
143564
def from_cn(cls, common_name):
        
        # search with cn
        result_cn = [(cert['id'], [cert['cn']] + cert['altnames'])
                     for cert in cls.list({'status': ['pending', 'valid'],
                                           'items_per_page': 500,
                                           'cn': common_name})]
        # search with altname
        result_alt = [(cert['id'], [cert['cn']] + cert['altnames'])
                      for cert in cls.list({'status': ['pending', 'valid'],
                                            'items_per_page': 500,
                                            'altname': common_name})]

        result = result_cn + result_alt
        ret = {}
        for id_, fqdns in result:
            for fqdn in fqdns:
                ret.setdefault(fqdn, []).append(id_)

        cert_id = ret.get(common_name)
        if not cert_id:
            return

        return cert_id
516623
def _get_and_verify_certificate_chain(
            server_info: ServerConnectivityInfo,
            trust_store: TrustStore
    ) -> Tuple[List[Certificate], str, Optional[OcspResponse]]:
        
        ssl_connection = server_info.get_preconfigured_ssl_connection(ssl_verify_locations=trust_store.path)

        # Enable OCSP stapling
        ssl_connection.ssl_client.set_tlsext_status_ocsp()

        try:  # Perform the SSL handshake
            ssl_connection.connect()

            ocsp_response = ssl_connection.ssl_client.get_tlsext_status_ocsp_resp()
            x509_cert_chain = ssl_connection.ssl_client.get_peer_cert_chain()
            (_, verify_str) = ssl_connection.ssl_client.get_certificate_chain_verify_result()

        except ClientCertificateRequested:  # The server asked for a client cert
            # We can get the server cert anyway
            ocsp_response = ssl_connection.ssl_client.get_tlsext_status_ocsp_resp()
            x509_cert_chain = ssl_connection.ssl_client.get_peer_cert_chain()
            (_, verify_str) = ssl_connection.ssl_client.get_certificate_chain_verify_result()

        finally:
            ssl_connection.close()

        # Parse the certificates using the cryptography module
        parsed_x509_chain = [load_pem_x509_certificate(x509_cert.as_pem().encode('ascii'), backend=default_backend())
                             for x509_cert in x509_cert_chain]
        return parsed_x509_chain, verify_str, ocsp_response