id is 'A' - 'F' for the various keys used by ssh
6146
def _compute_key(self, id, nbytes):
        """"""
        m = Message()
        m.add_mpint(self.K)
        m.add_bytes(self.H)
        m.add_byte(b(id))
        m.add_bytes(self.session_id)
        # Fallback to SHA1 for kex engines that fail to specify a hex
        # algorithm, or for e.g. transport tests that don't run kexinit.
        hash_algo = getattr(self.kex_engine, "hash_algo", None)
        hash_select_msg = "kex engine {} specified hash_algo {!r}".format(
            self.kex_engine.__class__.__name__, hash_algo
        )
        if hash_algo is None:
            hash_algo = sha1
            hash_select_msg += ", falling back to sha1"
        if not hasattr(self, "_logged_hash_selection"):
            self._log(DEBUG, hash_select_msg)
            setattr(self, "_logged_hash_selection", True)
        out = sofar = hash_algo(m.asbytes()).digest()
        while len(out) < nbytes:
            m = Message()
            m.add_mpint(self.K)
            m.add_bytes(self.H)
            m.add_bytes(sofar)
            digest = hash_algo(m.asbytes()).digest()
            out += digest
            sofar += digest
        return out[:nbytes]
16276
def convert_identifier_to_key(identifier):
        
        key = ''.join(c for c in identifier if c.isalnum() or c in '_.-')
        if len(key) > 230:
            key = key[:150] + '-' + hashlib.md5(key).hexdigest()

        return "%s_accesses" % key
971166
def remove_sshkey(host, known_hosts=None):
    '''
    
    '''
    if known_hosts is None:
        if 'HOME' in os.environ:
            known_hosts = '{0}/.ssh/known_hosts'.format(os.environ['HOME'])
        else:
            try:
                known_hosts = '{0}/.ssh/known_hosts'.format(
                    pwd.getpwuid(os.getuid()).pwd_dir
                )
            except Exception:
                pass

    if known_hosts is not None:
        log.debug(
            'Removing ssh key for %s from known hosts file %s',
            host, known_hosts
        )
    else:
        log.debug('Removing ssh key for %s from known hosts file', host)

    cmd = 'ssh-keygen -R {0}'.format(host)
    subprocess.call(cmd, shell=True)
1066568
def import_public_key(line):
    """"""
    log.debug('loading SSH public key: %r', line)
    file_type, base64blob, name = line.split()
    blob = base64.b64decode(base64blob)
    result = parse_pubkey(blob)
    result['name'] = name.encode('utf-8')
    assert result['type'] == file_type.encode('ascii')
    log.debug('loaded %s public key: %s', file_type, result['fingerprint'])
    return result
423016
def match_keys(inp, p=False):
    """"""
    _keys = []
    ssh_keys = DO.get_ssh_keys()
    for k in inp.split(","):
        done = False
        if k.isdigit():
            for _ in [s for s in ssh_keys if s["id"] == int(k)]:
                done = True
                _keys.append(_["fingerprint"])
        else:
            for _ in [s for s in ssh_keys if s["fingerprint"] == k]:
                done = True
                _keys.append(_["fingerprint"])
        if p and not done:
            print("Could not find a match for '{}', skipping".format(k), file=sys.stderr)
    return _keys
596554
def passwd_keys(self, username):
        
        keys = []
        if username == 'mysql':
            log("Bad username '%s'" % (username), level=WARNING)

        if username:
            # IMPORTANT: *newer* format must be returned first
            keys.append('mysql-%s.passwd' % (username))
            keys.append('%s.passwd' % (username))
        else:
            keys.append('mysql.passwd')

        for key in keys:
            yield key
172471
def _replace_auth_key(
        user,
        key,
        enc='ssh-rsa',
        comment='',
        options=None,
        config='.ssh/authorized_keys'):
    '''
    
    '''

    auth_line = _format_auth_line(key, enc, comment, options or [])

    lines = []
    full = _get_config_file(user, config)

    try:
        # open the file for both reading AND writing
        with salt.utils.files.fopen(full, 'r') as _fh:
            for line in _fh:
                # We don't need any whitespace-only containing lines or arbitrary doubled newlines
                line = salt.utils.stringutils.to_unicode(line.strip())
                if line == '':
                    continue
                line += '\n'

                if line.startswith('#'):
                    # Commented Line
                    lines.append(line)
                    continue
                comps = re.findall(r'((.*)\s)?(ssh-[a-z0-9-]+|ecdsa-[a-z0-9-]+)\s([a-zA-Z0-9+/]+={0,2})(\s(.*))?', line)
                if comps and len(comps[0]) > 3 and comps[0][3] == key:
                    # Found our key, replace it
                    lines.append(auth_line)
                else:
                    lines.append(line)
            _fh.close()
            # Re-open the file writable after properly closing it
            with salt.utils.files.fopen(full, 'wb') as _fh:
                # Write out any changes
                _fh.writelines(salt.utils.data.encode(lines))
    except (IOError, OSError) as exc:
        raise CommandExecutionError(
            'Problem reading or writing to key file: {0}'.format(exc)
        )
400981
def _get_key_info(self):
        """"""
        if self._key_info_cache is None:
            self._key_info_cache = ssh_key_info_from_key_data(self.key_id,
                                                              self.priv_key)
        return self._key_info_cache
1059796
def cli(env, identifier, out_file):
    """"""

    mgr = SoftLayer.SshKeyManager(env.client)

    key_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'SshKey')

    key = mgr.get_key(key_id)

    if out_file:
        with open(path.expanduser(out_file), 'w') as pub_file:
            pub_file.write(key['key'])

    table = formatting.KeyValueTable(['name', 'value'])
    table.add_row(['id', key['id']])
    table.add_row(['label', key.get('label')])
    table.add_row(['notes', key.get('notes', '-')])
    env.fout(table)
1069192
def info(gandi, resource, id, value):
    
    output_keys = ['name', 'fingerprint']
    if id:
        output_keys.append('id')

    if value:
        output_keys.append('value')

    ret = []
    for item in resource:
        sshkey = gandi.sshkey.info(item)
        ret.append(output_sshkey(gandi, sshkey, output_keys))

    return ret
253812
def _create_ssh_keys(self):
        
        ret, _, _ = utils.run_command(
            [
                'ssh-keygen',
                '-t',
                'rsa',
                '-m',
                'PEM',
                '-N',
                '',
                '-f',
                self.paths.ssh_id_rsa(),
            ]
        )
        if ret != 0:
            raise RuntimeError(
                'Failed to crate ssh keys at %s',
                self.paths.ssh_id_rsa(),
            )
581090
def get_fingerprint_from_public_key(pubkey):
    

    # TODO: why is there a tmpdir?
    with tempdir() as workdir:
        key = os.path.join(workdir, 'key.pub')
        with open(key, 'w') as fd:
            fd.write(pubkey)

        cmd = [
            'ssh-keygen',
            '-l',
            '-f', key,
        ]

        p = Subprocess(cmd)
        output = p.stdout.strip()
        bits, fingerprint, _ = output.split(' ', 2)
        return fingerprint
60843
def _get_ssh_public_key(self):
        """"""
        key = ipa_utils.generate_public_ssh_key(self.ssh_private_key_file)
        return '{user}:{key} {user}'.format(
            user=self.ssh_user,
            key=key.decode()
        )
1227544
def _handle_ssh_callback(self, submission_id, host, port, password):
        
        if host is not None:  # ignore late calls (a bit hacky, but...)
            obj = {
                "ssh_host": host,
                "ssh_port": port,
                "ssh_password": password
            }
            self._database.submissions.update_one({"_id": submission_id}, {"$set": obj})
999141
def rm_auth_key_from_file(user,
                          source,
                          config='.ssh/authorized_keys',
                          saltenv='base',
                          fingerprint_hash_type=None):
    '''
    
    '''
    lfile = __salt__['cp.cache_file'](source, saltenv)
    if not os.path.isfile(lfile):
        raise CommandExecutionError(
            'Failed to pull key file from salt file server'
        )

    s_keys = _validate_keys(lfile, fingerprint_hash_type)
    if not s_keys:
        err = (
            'No keys detected in {0}. Is file properly formatted?'.format(
                source
            )
        )
        log.error(err)
        __context__['ssh_auth.error'] = err
        return 'fail'
    else:
        rval = ''
        for key in s_keys:
            rval += rm_auth_key(
                user,
                key,
                config=config,
                fingerprint_hash_type=fingerprint_hash_type
            )
        # Due to the ability for a single file to have multiple keys, it's
        # possible for a single call to this function to have both "replace"
        # and "new" as possible valid returns. I ordered the following as I
        # thought best.
        if 'Key not removed' in rval:
            return 'Key not removed'
        elif 'Key removed' in rval:
            return 'Key removed'
        else:
            return 'Key not present'
495174
def get_key(s):
    '''
    
    '''
    start = s.find("[")
    end = s.find("]")
    if start == -1 or end == -1:
        return None
    if s[start + 1] == "'":
        start += 1
    if s[end - 1] == "'":
        end -= 1
    return s[start + 1:end]
1068939
def delete(self, key_id=None):
        
        url = self.bitbucket.url('DELETE_SSH_KEY', key_id=key_id)
        return self.bitbucket.dispatch('DELETE', url, auth=self.bitbucket.auth)