Export a X.509 certificate.

    Reads a certificate from one of the slots on the YubiKey.

    \b
    SLOT        PIV slot to read certificate from.
    CERTIFICATE File to write certificate to. Use '-' to use stdout.
543842
def export_certificate(ctx, slot, format, certificate):
    
    controller = ctx.obj['controller']
    try:
        cert = controller.read_certificate(slot)
    except APDUError as e:
        if e.sw == SW.NOT_FOUND:
            ctx.fail('No certificate found.')
        else:
            logger.error('Failed to read certificate from slot %s', slot,
                         exc_info=e)
    certificate.write(cert.public_bytes(encoding=format))
1300591
def postprocess_key_for_export(self, key, client_random, server_random,
                                   con_end, read_or_write, req_len):
        
        s = con_end + read_or_write
        s = (s == "clientwrite" or s == "serverread")

        if self.tls_version < 0x0300:
            return None
        elif self.tls_version == 0x0300:
            if s:
                tbh = key + client_random + server_random
            else:
                tbh = key + server_random + client_random
            export_key = _tls_hash_algs["MD5"]().digest(tbh)[:req_len]
        else:
            if s:
                tag = b"client write key"
            else:
                tag = b"server write key"
            export_key = self.prf(key,
                                  tag,
                                  client_random + server_random,
                                  req_len)
        return export_key
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()
1063873
def exportNewKey(fingerprint):
    
    log.info("Exporting key: %s" % fingerprint)

    keyfn = os.path.join(gpg.homedir,
                         fingerprint + '-8192-bit-key') + os.path.extsep

    pubkey = gpg.export_keys(fingerprint)
    seckey = gpg.export_keys(fingerprint, secret=True)
    subkey = gpg.export_keys(fingerprint, secret=True, subkeys=True)

    with open(keyfn + 'pub' + os.path.extsep + 'asc', 'w') as fh:
        fh.write(pubkey)
    with open(keyfn + 'sec' + os.path.extsep + 'asc', 'w') as fh:
        fh.write(seckey)
    with open(keyfn + 'sub' + os.path.extsep + 'asc', 'w') as fh:
        fh.write(subkey)
970872
def export_public_key(vk, label):
    
    key_type, blob = serialize_verifying_key(vk)
    log.debug('fingerprint: %s', fingerprint(blob))
    b64 = base64.b64encode(blob).decode('ascii')
    return u'{} {} {}\n'.format(key_type.decode('ascii'), b64, label)
759373
def load(self):
        """"""

        private = self.is_private()
        with open_tls_file(self.file_path, 'r', private=private) as fh:
            if private:
                self.x509 = crypto.load_privatekey(self.encoding, fh.read())
            else:
                self.x509 = crypto.load_certificate(self.encoding, fh.read())
            return self.x509
911473
def generate_certificates(base_dir, *peer_names, pubKeyDir=None,
                          secKeyDir=None, sigKeyDir=None,
                          verkeyDir=None, clean=True):
    ''' '''
    pubKeyDir = pubKeyDir or 'public_keys'
    secKeyDir = secKeyDir or 'private_keys'
    verkeyDir = verkeyDir or 'verif_keys'
    sigKeyDir = sigKeyDir or 'sig_keys'

    # keys_dir = os.path.join(base_dir, 'certificates')
    e_keys_dir = os.path.join(base_dir, '_enc')
    s_keys_dir = os.path.join(base_dir, '_sig')

    public_keys_dir = os.path.join(base_dir, pubKeyDir)
    secret_keys_dir = os.path.join(base_dir, secKeyDir)
    ver_keys_dir = os.path.join(base_dir, verkeyDir)
    sig_keys_dir = os.path.join(base_dir, sigKeyDir)

    # Create directories for certificates, remove old content if necessary
    for d in [e_keys_dir, s_keys_dir, public_keys_dir, secret_keys_dir,
              ver_keys_dir, sig_keys_dir]:
        if clean and os.path.exists(d):
            shutil.rmtree(d)
        os.makedirs(d, exist_ok=True)

    # create new keys in certificates dir
    for peer_name in peer_names:
        createEncAndSigKeys(e_keys_dir, s_keys_dir, peer_name)

    # move public keys to appropriate directory
    for keys_dir, pkdir, skdir in [
        (e_keys_dir, public_keys_dir, secret_keys_dir),
        (s_keys_dir, ver_keys_dir, sig_keys_dir)
    ]:
        moveKeyFilesToCorrectLocations(keys_dir, pkdir, skdir)

    shutil.rmtree(e_keys_dir)
    shutil.rmtree(s_keys_dir)

    print('Public keys in {}'.format(public_keys_dir))
    print('Private keys in {}'.format(secret_keys_dir))
    print('Verification keys in {}'.format(ver_keys_dir))
    print('Signing keys in {}'.format(sig_keys_dir))
94569
def process_ldiff(self, data, name):
        
        from cryptography.x509.base import load_der_x509_certificate
        reg = re.compile(r'binary::\s*([0-9a-zA-Z+/=\s\t\r\n]{20,})$', re.MULTILINE | re.DOTALL)
        matches = re.findall(reg, str(data))

        ret = []
        num_certs_found = 0
        for idx, match in enumerate(matches):
            match = re.sub('[\r\t\n\s]', '', match)
            try:
                bindata = base64.b64decode(match)
                x509 = load_der_x509_certificate(bindata, self.get_backend())

                self.num_ldiff_cert += 1
                sub = self.process_x509(x509, name=name, pem=False, source='ldiff-cert')
                ret.append(sub)

            except Exception as e:
                logger.debug('Error in line ldiff file processing %s, idx %s, matchlen %s : %s'
                             % (name, idx, len(match), e))
                self.trace_logger.log(e)
        return ret
930078
function saveX509($cert, $format = self::FORMAT_PEM)
    {
        if (!is_array($cert) || !isset($cert['tbsCertificate'])) {
            return false;
        }

        switch (true) {
            // "case !$a: case !$b: break; default: whatever();" is the same thing as "if ($a && $b) whatever()"
            case !($algorithm = $this->_subArray($cert, 'tbsCertificate/subjectPublicKeyInfo/algorithm/algorithm')):
            case is_object($cert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey']):
                break;
            default:
                switch ($algorithm) {
                    case 'rsaEncryption':
                        $cert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey']
                            = base64_encode("\0" . base64_decode(preg_replace('#-.+-|[\r\n]#', '', $cert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'])));
                        /* "[For RSA keys] the parameters field MUST have ASN.1 type NULL for this algorithm identifier."
                           -- https://tools.ietf.org/html/rfc3279#section-2.3.1

                           given that and the fact that RSA keys appear ot be the only key type for which the parameters field can be blank,
                           it seems like perhaps the ASN.1 description ought not say the parameters field is OPTIONAL, but whatever.
                         */
                        $cert['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['parameters'] = null;
                        // https://tools.ietf.org/html/rfc3279#section-2.2.1
                        $cert['signatureAlgorithm']['parameters'] = null;
                        $cert['tbsCertificate']['signature']['parameters'] = null;
                }
        }

        $asn1 = new ASN1();
        $asn1->loadOIDs($this->oids);

        $filters = array();
        $type_utf8_string = array('type' => ASN1::TYPE_UTF8_STRING);
        $filters['tbsCertificate']['signature']['parameters'] = $type_utf8_string;
        $filters['tbsCertificate']['signature']['issuer']['rdnSequence']['value'] = $type_utf8_string;
        $filters['tbsCertificate']['issuer']['rdnSequence']['value'] = $type_utf8_string;
        $filters['tbsCertificate']['subject']['rdnSequence']['value'] = $type_utf8_string;
        $filters['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['parameters'] = $type_utf8_string;
        $filters['signatureAlgorithm']['parameters'] = $type_utf8_string;
        $filters['authorityCertIssuer']['directoryName']['rdnSequence']['value'] = $type_utf8_string;
        //$filters['policyQualifiers']['qualifier'] = $type_utf8_string;
        $filters['distributionPoint']['fullName']['directoryName']['rdnSequence']['value'] = $type_utf8_string;
        $filters['directoryName']['rdnSequence']['value'] = $type_utf8_string;

        /* in the case of policyQualifiers/qualifier, the type has to be \phpseclib\File\ASN1::TYPE_IA5_STRING.
           \phpseclib\File\ASN1::TYPE_PRINTABLE_STRING will cause OpenSSL's X.509 parser to spit out random
           characters.
         */
        $filters['policyQualifiers']['qualifier']
            = array('type' => ASN1::TYPE_IA5_STRING);

        $asn1->loadFilters($filters);

        $this->_mapOutExtensions($cert, 'tbsCertificate/extensions', $asn1);
        $this->_mapOutDNs($cert, 'tbsCertificate/issuer/rdnSequence', $asn1);
        $this->_mapOutDNs($cert, 'tbsCertificate/subject/rdnSequence', $asn1);

        $cert = $asn1->encodeDER($cert, $this->Certificate);

        switch ($format) {
            case self::FORMAT_DER:
                return $cert;
            // case self::FORMAT_PEM:
            default:
                return "-----BEGIN CERTIFICATE-----\r\n" . chunk_split(base64_encode($cert), 64) . '-----END CERTIFICATE-----';
        }
    }
547815
def save_x509s(self, x509s):
        """"""

        for file_type in TLSFileType:
            if file_type.value in x509s:
                x509 = x509s[file_type.value]
                if file_type is not TLSFileType.CA:
                    # persist this key or cert to disk
                    tlsfile = getattr(self, file_type.value)
                    if tlsfile:
                        tlsfile.save(x509)
850220
def get_certificate(self, filename):
        
        cert = self.get_certificate_der(filename)
        certificate = x509.Certificate.load(cert)

        return certificate
440605
function loadX509($cert, $mode = self::FORMAT_AUTO_DETECT)
    {
        if (is_array($cert) && isset($cert['tbsCertificate'])) {
            unset($this->currentCert);
            unset($this->currentKeyIdentifier);
            $this->dn = $cert['tbsCertificate']['subject'];
            if (!isset($this->dn)) {
                return false;
            }
            $this->currentCert = $cert;

            $currentKeyIdentifier = $this->getExtension('id-ce-subjectKeyIdentifier');
            $this->currentKeyIdentifier = is_string($currentKeyIdentifier) ? $currentKeyIdentifier : null;

            unset($this->signatureSubject);

            return $cert;
        }

        $asn1 = new ASN1();

        if ($mode != self::FORMAT_DER) {
            $newcert = $this->_extractBER($cert);
            if ($mode == self::FORMAT_PEM && $cert == $newcert) {
                return false;
            }
            $cert = $newcert;
        }

        if ($cert === false) {
            $this->currentCert = false;
            return false;
        }

        $asn1->loadOIDs($this->oids);
        $decoded = $asn1->decodeBER($cert);

        if (!empty($decoded)) {
            $x509 = $asn1->asn1map($decoded[0], $this->Certificate);
        }
        if (!isset($x509) || $x509 === false) {
            $this->currentCert = false;
            return false;
        }

        $this->signatureSubject = substr($cert, $decoded[0]['content'][0]['start'], $decoded[0]['content'][0]['length']);

        if ($this->_isSubArrayValid($x509, 'tbsCertificate/extensions')) {
            $this->_mapInExtensions($x509, 'tbsCertificate/extensions', $asn1);
        }
        $this->_mapInDNs($x509, 'tbsCertificate/issuer/rdnSequence', $asn1);
        $this->_mapInDNs($x509, 'tbsCertificate/subject/rdnSequence', $asn1);

        $key = &$x509['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'];
        $key = $this->_reformatKey($x509['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['algorithm'], $key);

        $this->currentCert = $x509;
        $this->dn = $x509['tbsCertificate']['subject'];

        $currentKeyIdentifier = $this->getExtension('id-ce-subjectKeyIdentifier');
        $this->currentKeyIdentifier = is_string($currentKeyIdentifier) ? $currentKeyIdentifier : null;

        return $x509;
    }
1010192
public static X509CertificateHolder getX509CertificateHolder(CertifiedPublicKey cert)
    {
        if (cert instanceof BcX509CertifiedPublicKey) {
            return ((BcX509CertifiedPublicKey) cert).getX509CertificateHolder();
        } else {
            try {
                return new X509CertificateHolder(cert.getEncoded());
            } catch (IOException e) {
                // Very unlikely
                throw new IllegalArgumentException("Invalid certified public key, unable to encode.");
            }
        }

    }
1287338
function saveX509($cert)
    {
        if (!is_array($cert) || !isset($cert['tbsCertificate'])) {
            return false;
        }

        if (is_array($cert['tbsCertificate']['subjectPublicKeyInfo'])) {
            switch ($cert['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['algorithm']) {
                case 'rsaEncryption':
                    $cert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'] = 
                        base64_encode("\0" . base64_decode(preg_replace('#-.+-|[\r\n]#', '', $cert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'])));
            }
        }

        $asn1 = new File_ASN1();

        $asn1->loadOIDs($this->oids);

        $filters = array();
        $filters['tbsCertificate']['signature']['parameters'] = 
        $filters['tbsCertificate']['signature']['issuer']['rdnSequence']['value'] = 
        $filters['tbsCertificate']['issuer']['rdnSequence']['value'] = 
        $filters['tbsCertificate']['subject']['rdnSequence']['value'] = 
        $filters['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['parameters'] = 
        $filters['signatureAlgorithm']['parameters'] = 
        $filters['authorityCertIssuer']['directoryName']['rdnSequence']['value'] = 
        //$filters['policyQualifiers']['qualifier'] = 
        $filters['distributionPoint']['fullName']['directoryName']['rdnSequence']['value'] = 
        $filters['directoryName']['rdnSequence']['value'] = 
            array('type' => FILE_ASN1_TYPE_UTF8_STRING);
        /* in the case of policyQualifiers/qualifier, the type has to be FILE_ASN1_TYPE_IA5_STRING.
           FILE_ASN1_TYPE_PRINTABLE_STRING will cause OpenSSL's X.509 parser to spit out random
           characters.
         */
        $filters['policyQualifiers']['qualifier'] = 
            array('type' => FILE_ASN1_TYPE_IA5_STRING);

        $asn1->loadFilters($filters);

        $this->_mapOutExtensions($cert, 'tbsCertificate/extensions', $asn1);

        $cert = $asn1->encodeDER($cert, $this->Certificate);

        return "-----BEGIN CERTIFICATE-----\r\n" . chunk_split(base64_encode($cert)) . '-----END CERTIFICATE-----';
    }
903795
def get_public_key(key_info, ctx):
        
        x509_certificate = key_info.find(
            'ds:KeyInfo/ds:X509Data/ds:X509Certificate',
            namespaces={'ds': ns.DSigNs}
        )
        if x509_certificate is not None:
            return load_der_x509_certificate(
                base64.b64decode(x509_certificate.text),
                default_backend()
            ).public_key()
        if ctx.public_key is not None:
            return ctx.public_key
        if isinstance(ctx.private_key, (str, bytes)):
            return ctx.private_key
        return ctx.private_key.public_key()
139984
@SneakyThrows
    public X509Certificate loadCert(String certLocation) {
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        Resource certRes = resourceLoader.getResource(certLocation);
        X509Certificate cert = (X509Certificate) cf.generateCertificate(certRes.getInputStream());
        return cert;
    }
89525
def generate_certificates(base_dir: str, remove_certificates: bool=False):
    ''' '''
    public_keys_dir = os.path.join(base_dir, 'public_keys')
    secret_keys_dir = os.path.join(base_dir, 'private_keys')

    # Make the public and private key directories
    for path in (public_keys_dir, secret_keys_dir):
        if not os.path.exists(path):
            os.mkdir(path)

    # create new keys in certificates dir
    server_public_file, server_secret_file = zmq.auth.create_certificates(base_dir, "vexbot")
    client_public_file, client_secret_file = zmq.auth.create_certificates(base_dir, "client")

    vexbot_public = os.path.join(public_keys_dir, 'vexbot.key')
    client_public = os.path.join(public_keys_dir, 'client.key')

    vexbot_secret = os.path.join(secret_keys_dir, 'vexbot.key_secret')
    client_secret = os.path.join(secret_keys_dir, 'client.key_secret')

    if os.path.exists(vexbot_public) and remove_certificates:
        os.unlink(vexbot_public)
        try:
            os.unlink(vexbot_secret)
        except OSError:
            pass
    elif os.path.exists(vexbot_public) and not remove_certificates:
        os.unlink(server_public_file)
        os.unlink(server_secret_file)

    if os.path.exists(client_public) and remove_certificates:
        os.unlink(client_public)
        try:
            os.unlink(client_secret)
        except OSError:
            pass
    elif os.path.exists(client_public) and not remove_certificates:
        os.unlink(client_public_file)
        os.unlink(client_secret_file)

    # move public keys to appropriate directory
    for key_file in os.listdir(base_dir):
        if key_file.endswith(".key"):
            shutil.move(os.path.join(base_dir, key_file),
                        os.path.join(public_keys_dir, '.'))

    # move secret keys to appropriate directory
    for key_file in os.listdir(base_dir):
        if key_file.endswith(".key_secret"):
            shutil.move(os.path.join(base_dir, key_file),
                        os.path.join(secret_keys_dir, '.'))