Export certificate in 'fmt' format (DER or PEM) to file 'filename'
193173
def export(self, filename, fmt="DER"):
        
        f = open(filename, "wb")
        if fmt == "DER":
            f.write(self.der)
        elif fmt == "PEM":
            f.write(self.pem)
        f.close()
257426
def certificate(self, value):
        """"""
        import os
        if os.path.isfile(value):
            self._certificatefile = value
615568
private byte[] encodePKIPATH() throws CertificateEncodingException {

        ListIterator<X509Certificate> li = certs.listIterator(certs.size());
        try {
            DerOutputStream bytes = new DerOutputStream();
            // encode certs in reverse order (trust anchor to target)
            // according to PkiPath format
            while (li.hasPrevious()) {
                X509Certificate cert = li.previous();
                // check for duplicate cert
                if (certs.lastIndexOf(cert) != certs.indexOf(cert)) {
                    throw new CertificateEncodingException
                        ("Duplicate Certificate");
                }
                // get encoded certificates
                byte[] encoded = cert.getEncoded();
                bytes.write(encoded);
            }

            // Wrap the data in a SEQUENCE
            DerOutputStream derout = new DerOutputStream();
            derout.write(DerValue.tag_SequenceOf, bytes);
            return derout.toByteArray();

        } catch (IOException ioe) {
           throw new CertificateEncodingException("IOException encoding " +
                   "PkiPath data: " + ioe, ioe);
        }
    }
1297778
def getGroupsURL(certfile, group):
    """"""

    GMS = "https://" + _SERVER + _GMS

    certfile.seek(0)
    buf = certfile.read()

    x509 = crypto.load_certificate(crypto.FILETYPE_PEM, buf)
    sep = ""
    dn = ""
    parts = []
    for i in x509.get_issuer().get_components():
        #print i
        if i[0] in parts:
            continue
        parts.append(i[0])
        dn = i[0] + "=" + i[1] + sep + dn
        sep = ","

    return GMS + "/" + group + "/" + urllib.quote(dn)
508349
def acme_sign_certificate(common_name, size=DEFAULT_KEY_SIZE):
    '''
        
    '''
    private_key_path = '{}/{}.key'.format(CERTIFICATES_PATH, common_name)
    certificate_path = '{}/{}.crt'.format(CERTIFICATES_PATH, common_name)
    certificate_request_path = '{}/{}.csr'.format(CERTIFICATES_PATH,
                                                  common_name)
    signed_cert = '{certificates_path}/{common_name}-signed.crt'.format(
        certificates_path=CERTIFICATES_PATH,
        common_name=common_name)

    generate_certificate(common_name, size)

    cmd = 'openssl req -new -sha256 -key {private_key_path}'
    cmd += ' -subj "/CN={common_name}" -out {certificate_request_path}'
    cmd = cmd.format(
        private_key_path=private_key_path,
        common_name=common_name,
        certificate_request_path=certificate_request_path
    )
    p = subprocess.Popen(cmd,
                         shell=True,
                         stdout=subprocess.PIPE,
                         close_fds=True)
    p.communicate()

    _internal_sign_certificate(certificate_path, certificate_request_path,
                              signed_cert)

    cron = "/etc/cron.monthly/acme-renew"
    if not os.path.exists(cron):
        with open(cron, "w") as file:
            file.write("#!/bin/bash\ncozy_management renew_certificates\n")
        st = os.stat(cron)
        os.chmod(cron, st.st_mode | S_IXUSR)
128146
def import_public_rsa_key_from_file(filename):
    
    with open(filename, "rb") as key_file:
        public_key = serialization.load_pem_public_key(
            key_file.read(),
            backend=default_backend())
    return public_key
737087
def objectsFromPEM(pemdata):
    
    certificates = []
    keys = []
    blobs = [b""]
    for line in pemdata.split(b"\n"):
        if line.startswith(b'-----BEGIN'):
            if b'CERTIFICATE' in line:
                blobs = certificates
            else:
                blobs = keys
            blobs.append(b'')
        blobs[-1] += line
        blobs[-1] += b'\n'
    keys = [KeyPair.load(key, FILETYPE_PEM) for key in keys]
    certificates = [Certificate.loadPEM(certificate)
                    for certificate in certificates]
    return PEMObjects(keys=keys, certificates=certificates)
689109
public static void saveX509Cert( Certificate[] certs, File certFile ) throws GeneralSecurityException, IOException
    {
        try ( BufferedWriter writer = new BufferedWriter( new FileWriter( certFile ) ) )
        {
            for ( Certificate cert : certs )
            {
                String certStr = Base64.getEncoder().encodeToString( cert.getEncoded() ).replaceAll( "(.{64})", "$1\n" );

                writer.write( BEGIN_CERT );
                writer.newLine();

                writer.write( certStr );
                writer.newLine();

                writer.write( END_CERT );
                writer.newLine();
            }
        }
    }
960548
def serialize_cert_to_der(cert_obj):
    
    return cert_obj.public_bytes(
        cryptography.hazmat.primitives.serialization.Encoding.DER
    )
942005
def makeCredentials(path, email):
    
    key = _generateKey()
    cert = _makeCertificate(key, email)

    certPath = path.child("client.pem")
    certPath.alwaysCreate = True

    with certPath.open("wb") as pemFile:
        pemFile.write(dump_privatekey(FILETYPE_PEM, key))
        pemFile.write(dump_certificate(FILETYPE_PEM, cert))
352423
function readCertificateDataFromFile ({ keyFile, certFile, caFile }) {
  let key, cert, ca;

  if (keyFile) {
    key = fs.readFileSync(keyFile);
  }

  if (certFile) {
    cert = fs.readFileSync(certFile);
  }

  if (caFile) {
    ca = fs.readFileSync(caFile);
  }

  return { key, cert, ca };
}
943368
def save(file)
      File.open(file, "w") do |f|
        f.write(@raw_cert.to_pem)
      end
      true
    end
552149
def Convert(self, metadata, process, token=None):
    """"""

    for f in process.open_files:
      yield ExportedOpenFile(metadata=metadata, pid=process.pid, path=f)
174415
def export_pipeline(conf, args):
    """"""
    # Export the source pipeline and save it to file
    src = conf.config['instances'][args.src_instance]
    src_url = api.build_pipeline_url(build_instance_url(src))
    src_auth = tuple([conf.creds['instances'][args.src_instance]['user'],
                      conf.creds['instances'][args.src_instance]['pass']])
    verify_ssl = src.get('verify_ssl', True)
    export_json = api.export_pipeline(src_url, args.src_pipeline_id, src_auth, verify_ssl)
    with open(args.out, 'w') as outFile:
        outFile.write(json.dumps(export_json, indent=4, sort_keys=False))
        return (0, '')
817725
def savePkeyPem(self, pkey, path):
        '''
        
        '''
        with s_common.genfile(path) as fd:
            fd.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
1041419
def save_figure_tofile(fig, fmt, fname):
    """"""
    root, ext = osp.splitext(fname)
    if ext == '.png' and fmt == 'image/svg+xml':
        qimg = svg_to_image(fig)
        qimg.save(fname)
    else:
        if fmt == 'image/svg+xml' and is_unicode(fig):
            fig = fig.encode('utf-8')

        with open(fname, 'wb') as f:
            f.write(fig)
687827
def grab_keyfile(cert_url):
    
    key_cache = caches[getattr(settings, 'BOUNCY_KEY_CACHE', 'default')]

    pemfile = key_cache.get(cert_url)
    if not pemfile:
        response = urlopen(cert_url)
        pemfile = response.read()
        # Extract the first certificate in the file and confirm it's a valid
        # PEM certificate
        certificates = pem.parse(smart_bytes(pemfile))

        # A proper certificate file will contain 1 certificate
        if len(certificates) != 1:
            logger.error('Invalid Certificate File: URL %s', cert_url)
            raise ValueError('Invalid Certificate File')

        key_cache.set(cert_url, pemfile)
    return pemfile