Export public key to text format.

    The resulting string can be written into a .pub file or
    appended to the ~/.ssh/authorized_keys file.
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)
362230
def export_public_key(self):
		
		if self.__public_key is None:
			raise ValueError('Unable to call this method. Public key must be set')

		return self.__public_key.public_bytes(
			encoding=serialization.Encoding.PEM,
			format=serialization.PublicFormat.SubjectPublicKeyInfo
		)
1097612
def from_pubkey_file(cls, file):
        """"""
        if hasattr(file, 'read'):
            return cls.from_pubkey_line(file.read())

        return cls.from_pubkey_line(open(file).read())
711743
def fingerprint_from_raw_ssh_pub_key(key):
    
    fp_plain = hashlib.md5(key).hexdigest()
    return ':'.join(a + b for a, b in zip(fp_plain[::2], fp_plain[1::2]))
717646
def decode_pubkey_hex(pubkey_hex):
    
    if not isinstance(pubkey_hex, (str, unicode)):
        raise ValueError("public key is not a string")

    pubk = keylib.key_formatting.decompress(str(pubkey_hex))
    assert len(pubk) == 130

    pubk_raw = pubk[2:]
    pubk_i = (int(pubk_raw[:64], 16), int(pubk_raw[64:], 16))
    return pubk_i
580912
def serialize_verifying_key(vk):
    
    if isinstance(vk, ed25519.keys.VerifyingKey):
        pubkey = vk.to_bytes()
        key_type = SSH_ED25519_KEY_TYPE
        blob = util.frame(SSH_ED25519_KEY_TYPE) + util.frame(pubkey)
        return key_type, blob

    if isinstance(vk, ecdsa.keys.VerifyingKey):
        curve_name = SSH_NIST256_CURVE_NAME
        key_blob = SSH_NIST256_DER_OCTET + vk.to_string()
        parts = [SSH_NIST256_KEY_TYPE, curve_name, key_blob]
        key_type = SSH_NIST256_KEY_TYPE
        blob = b''.join([util.frame(p) for p in parts])
        return key_type, blob

    raise TypeError('unsupported {!r}'.format(vk))
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
581946
def to_script_pubkey
      v = ver == 0 ? ver : ver + 0x50
      ([v, prog.length].pack("CC") + prog.map{|p|[p].pack("C")}.join).unpack('H*').first
    end
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)
        )
908225
def generate_public_ssh_key(ssh_private_key_file):
    """"""
    try:
        with open(ssh_private_key_file, "rb") as key_file:
            key = key_file.read()
    except FileNotFoundError:
        raise IpaUtilsException(
            'SSH private key file: %s cannot be found.' % ssh_private_key_file
        )

    try:
        private_key = serialization.load_pem_private_key(
            key,
            password=None,
            backend=default_backend()
        )
    except ValueError:
        raise IpaUtilsException(
            'SSH private key file: %s is not a valid key file.'
            % ssh_private_key_file
        )

    return private_key.public_key().public_bytes(
        serialization.Encoding.OpenSSH,
        serialization.PublicFormat.OpenSSH
    )
12183
def decompress_pubkey(pubkey, curve_name):
    
    vk = None
    if len(pubkey) == 33:
        decompress = {
            CURVE_NIST256: _decompress_nist256,
            CURVE_ED25519: _decompress_ed25519,
            ECDH_CURVE25519: _decompress_ed25519,
        }[curve_name]
        vk = decompress(pubkey)

    if not vk:
        msg = 'invalid {!s} public key: {!r}'.format(curve_name, pubkey)
        raise ValueError(msg)

    return vk
1080196
function loadKeyPair (pub, prv, use) {
  var pubPEM, prvPEM, pubJWK

  try {
    pubPEM = fs.readFileSync(pub).toString('ascii')
  } catch (e) {
    throw new Error('Unable to read the public key from ' + pub)
  }

  try {
    prvPEM = fs.readFileSync(prv).toString('ascii')
  } catch (e) {
    throw new Error('Unable to read the private key from ' + pub)
  }

  try {
    pubJWK = pemjwk.pem2jwk(pubPEM)
  } catch (e) {
    throw new Error('Unable to convert the public key ' + pub + ' to a JWK')
  }

  return {
    pem: {
      pub: pubPEM,
      prv: prvPEM
    },
    jwk: {
      pub: {
        kty: pubJWK.kty,
        use: use,
        alg: 'RS256',
        n: pubJWK.n,
        e: pubJWK.e
      }
    }
  }
}
113245
def to_signed_str(self, private, public, passphrase=None):
        '''
        
        '''
        from pyxmli import xmldsig
        try:
            from Crypto.PublicKey import RSA
        except ImportError:
            raise ImportError('PyCrypto 2.5 or more recent module is ' \
                              'required to enable XMLi signing.\n' \
                              'Please visit: http://pycrypto.sourceforge.net/')
            
        if not isinstance(private, RSA._RSAobj):
            private = RSA.importKey(private.read(), passphrase=passphrase)
        
        if not isinstance(public, RSA._RSAobj):
            public = RSA.importKey(public.read())
            
        return to_unicode(xmldsig.sign(to_unicode(self.to_string()),
                                       private, public))
1276623
def extract(input, output):
    
    log("Loading paillier keypair")
    priv = json.load(input)
    error_msg = "Invalid private key"
    assert 'pub' in priv, error_msg
    assert priv['kty'] == 'DAJ', error_msg
    json.dump(priv['pub'], output)
    output.write('\n')
    log("Public key written to {}".format(output.name))
172225
function export_key($key, $fp = null, $include_private = false)
    {
        $this->load_pgp_driver();
        $result = $this->pgp_driver->export($key, $include_private, $this->get_passwords());

        if ($result instanceof enigma_error) {
            self::raise_error($result, __LINE__);
            return $result;
        }

        if ($fp) {
            fwrite($fp, $result);
        }
        else {
            return $result;
        }
    }
701555
def __generateSPK(self):
        

        key = self.__KeyPair.generate()

        key_serialized = self.__PublicKeyEncoder.encodePublicKey(
            key.pub,
            self.__curve
        )

        signature = self.__XEdDSA(mont_priv = self.__ik.priv).sign(key_serialized)

        self.__spk = {
            "key": key,
            "signature": signature,
            "timestamp": time.time()
        }
229178
def export_private_key(self, password=None):
		

		if self.__private_key is None:
			raise ValueError('Unable to call this method. Private key must be set')

		if password is not None:
			if isinstance(password, str) is True:
				password = password.encode()
			return self.__private_key.private_bytes(
				encoding=serialization.Encoding.PEM,
				format=serialization.PrivateFormat.PKCS8,
				encryption_algorithm=serialization.BestAvailableEncryption(password)
			)
		return self.__private_key.private_bytes(
			encoding=serialization.Encoding.PEM,
			format=serialization.PrivateFormat.TraditionalOpenSSL,
			encryption_algorithm=serialization.NoEncryption()
		)