Writes GPG key material into a file at a provided path.

    :param key_name: A key name to use for a key file (could be a fingerprint)
    :type key_name: str
    :param key_material: A GPG key material (binary)
    :type key_material: (str, bytes)
505640
def _write_apt_gpg_keyfile(key_name, key_material):
    
    with open('/etc/apt/trusted.gpg.d/{}.gpg'.format(key_name),
              'wb') as keyf:
        keyf.write(key_material)
1121326
function writeWallet( path, keys ){
 	var data = "";
 	for( var i=0; i<keys.length; i++ ){
 		var key = keys[i];
		if( i > 0 ) data += "\n";
 		data += key.wifC+"	"+key.label;
 	}
 	try{
 		FS.writeFileSync( path, data, { encoding: "utf8", mode: 0600 } );
 	}
 	catch(err){
		throw new Err.FileSystemError(err); 
 	}
 }
599361
def _register_key(fingerprint, gpg):
    """"""

    for private_key in gpg.list_keys(True):
        try:
            if str(fingerprint) == private_key['fingerprint']:
                config["gpg_key_fingerprint"] = \
                    repr(private_key['fingerprint'])
        except KeyError:
            pass
314744
def write_new_key
      File.open(full_key_path, 'w') do |f|
        f.write OpenSSL::PKey::RSA.generate(1024).export()
      end
    end
340706
def describe_keypairs(self, xml_bytes):
        
        results = []
        root = XML(xml_bytes)
        keypairs = root.find("keySet")
        if keypairs is None:
            return results
        for keypair_data in keypairs:
            key_name = keypair_data.findtext("keyName")
            key_fingerprint = keypair_data.findtext("keyFingerprint")
            results.append(model.Keypair(key_name, key_fingerprint))
        return results
486926
def create_key(self, title, key):
        
        created = None

        if title and key:
            url = self._build_url('user', 'keys')
            req = self._post(url, data={'title': title, 'key': key})
            json = self._json(req, 201)
            if json:
                created = Key(json, self)
        return created
745051
function RecordKey(path, recordType, name) {
    this.path = LedgerPath.parse(path);
    this.recordType = recordType;
    this.name = name;
}
365045
def suitability_as_key(self, key_name):
        
        pk_values = all_values_for(self, key_name)
        if not pk_values:
            return ('absent', int)  # could still use it
        key_type = type(th.best_coercable(pk_values))
        num_unique_values = len(set(pk_values))
        if num_unique_values < len(pk_values):
            return (False, None)     # non-unique
        if num_unique_values == len(self):
            return (True, key_type)  # perfect!
        return ('partial', key_type)
1198126
def insert_hash(path: Path, content: Union[str, bytes], *, hash_length=7, hash_algorithm=hashlib.md5):
    
    if isinstance(content, str):
        content = content.encode()
    hash_ = hash_algorithm(content).hexdigest()[:hash_length]
    if '.' in path.name:
        new_name = re.sub(r'\.', f'.{hash_}.', path.name, count=1)
    else:
        new_name = f'{path.name}.{hash_}'
    return path.with_name(new_name)
1142698
def gen_keys_signature(self, priv, pub, signature_path, auto_create=False, keysize=None):
        '''
        
        '''
        # check given pub-key
        if pub:
            if not os.path.isfile(pub):
                return 'Public-key {0} does not exist'.format(pub)
        # default to master.pub
        else:
            mpub = self.opts['pki_dir'] + '/' + 'master.pub'
            if os.path.isfile(mpub):
                pub = mpub

        # check given priv-key
        if priv:
            if not os.path.isfile(priv):
                return 'Private-key {0} does not exist'.format(priv)
        # default to master_sign.pem
        else:
            mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem'
            if os.path.isfile(mpriv):
                priv = mpriv

        if not priv:
            if auto_create:
                log.debug(
                    'Generating new signing key-pair .%s.* in %s',
                    self.opts['master_sign_key_name'], self.opts['pki_dir']
                )
                salt.crypt.gen_keys(self.opts['pki_dir'],
                                    self.opts['master_sign_key_name'],
                                    keysize or self.opts['keysize'],
                                    self.opts.get('user'),
                                    self.passphrase)

                priv = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem'
            else:
                return 'No usable private-key found'

        if not pub:
            return 'No usable public-key found'

        log.debug('Using public-key %s', pub)
        log.debug('Using private-key %s', priv)

        if signature_path:
            if not os.path.isdir(signature_path):
                log.debug('target directory %s does not exist', signature_path)
        else:
            signature_path = self.opts['pki_dir']

        sign_path = signature_path + '/' + self.opts['master_pubkey_signature']

        skey = get_key(self.opts)
        return skey.gen_signature(priv, pub, sign_path)
1170448
def GetKeyByPath(self, key_path):
    
    key_path_upper = key_path.upper()
    if key_path_upper.startswith(self._key_path_prefix_upper):
      relative_key_path = key_path[self._key_path_prefix_length:]
    elif key_path.startswith(definitions.KEY_PATH_SEPARATOR):
      relative_key_path = key_path
      key_path = ''.join([self._key_path_prefix, key_path])
    else:
      return None

    path_segments = key_paths.SplitKeyPath(relative_key_path)
    registry_key = self._root_key
    if not registry_key:
      return None

    for path_segment in path_segments:
      registry_key = registry_key.GetSubkeyByName(path_segment)
      if not registry_key:
        return None

    return registry_key
953413
def generate_signing_key(args):
    
    if os.path.exists(args.keyfile):
        raise esptool.FatalError("ERROR: Key file %s already exists" % args.keyfile)
    sk = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p)
    with open(args.keyfile, "wb") as f:
        f.write(sk.to_pem())
    print("ECDSA NIST256p private key in PEM format written to %s" % args.keyfile)
1302880
function generateKeyPair (name, { output }) {
  const { publicKey, secretKey } = Crypto.generateKeyPair()

  const data = [
    [path.join(output, name), secretKey],
    [path.join(output, `${name}.pub`), publicKey]
  ]

  data.forEach(([path, data]) => {
    fs.writeFileSync(path, data)
    console.log(`Wrote ${path}`)
  })
}
826541
def _GenerateSshKey(self, key_type, key_dest):
    
    # Create a temporary file to save the created RSA keys.
    with tempfile.NamedTemporaryFile(prefix=key_type, delete=True) as temp:
      temp_key = temp.name

    command = ['ssh-keygen', '-t', key_type, '-f', temp_key, '-N', '', '-q']
    try:
      self.logger.info('Generating SSH key %s.', key_dest)
      subprocess.check_call(command)
    except subprocess.CalledProcessError:
      self.logger.warning('Could not create SSH key %s.', key_dest)
      return

    shutil.move(temp_key, key_dest)
    shutil.move('%s.pub' % temp_key, '%s.pub' % key_dest)

    file_utils.SetPermissions(key_dest, mode=0o600)
    file_utils.SetPermissions('%s.pub' % key_dest, mode=0o644)
1349660
def create(key_name: str, sections: List[str]): # -> NoParserFoundForObject:
        
        return MultipleKeyOccurenceInConfigurationError('Cannot read the provided config file as a flat dictionary : '
                                                        'key \'' + key_name + '\' appears several times, in sections'
                                                                              '\'' + str(sections) + '\'.')
819501
def _save_keyring(self, keyring_dict):
        """"""
        import gdata
        result = self.OK
        file_contents = base64.urlsafe_b64encode(pickle.dumps(keyring_dict))
        try:
            if self.docs_entry:
                extra_headers = {'Content-Type': 'text/plain',
                                 'Content-Length': len(file_contents)}
                self.docs_entry = self.client.Put(
                    file_contents,
                    self.docs_entry.GetEditMediaLink().href,
                    extra_headers=extra_headers
                )
            else:
                from gdata.docs.service import DocumentQuery
                # check for existence of folder, create if required
                folder_query = DocumentQuery(categories=['folder'])
                folder_query['title'] = self.collection
                folder_query['title-exact'] = 'true'
                docs = self.client.QueryDocumentListFeed(folder_query.ToUri())
                if docs.entry:
                    folder_entry = docs.entry[0]
                else:
                    folder_entry = self.client.CreateFolder(self.collection)
                file_handle = io.BytesIO(file_contents)
                media_source = gdata.MediaSource(
                    file_handle=file_handle,
                    content_type='text/plain',
                    content_length=len(file_contents),
                    file_name='temp')
                self.docs_entry = self.client.Upload(
                    media_source,
                    self._get_doc_title(),
                    folder_or_uri=folder_entry
                )
        except gdata.service.RequestError as ex:
            try:
                if ex.message['reason'].lower().find('conflict') != -1:
                    result = self.CONFLICT
                else:
                    # Google docs has a bug when updating a shared document
                    # using PUT from any account other that the owner.
                    # It returns an error 400 "Sorry, there was an error saving
                    # the file. Please try again"
                    # *despite* actually updating the document!
                    # Workaround by re-reading to see if it actually updated
                    msg = 'Sorry, there was an error saving the file'
                    if ex.message['body'].find(msg) != -1:
                        new_docs_entry, new_keyring_dict = self._read()
                        if new_keyring_dict == keyring_dict:
                            result = self.OK
                        else:
                            result = self.FAIL
                    else:
                        result = self.FAIL
            except Exception:
                result = self.FAIL

        return result
287529
def pack_buffer(self, key):
        
        self.finish_buffer_write(key)
        file_path = self.items_group_files.get_current_buffer_file_for_group(key).path
        file_hash = None
        if self.hash_algorithm:
            file_hash = hash_for_file(file_path, self.hash_algorithm)

        file_size = os.path.getsize(file_path)
        write_info = {
            'number_of_records': self.grouping_info[key]['buffered_items'],
            'file_path': file_path,
            'size': file_size,
            'file_hash': file_hash,
        }
        self.set_metadata_for_file(file_path, **write_info)
        return write_info