Encode a raw SSH key (string of bytes, as from
    `str(paramiko.AgentKey)`) to a fingerprint in the SHA256 form:
        SHA256:j2WoSeOWhFy69BQ39fuafFAySp9qCZTSCEyT2vRKcL+s
775938
def sha256_fingerprint_from_raw_ssh_pub_key(raw_key):
    
    digest = hashlib.sha256(raw_key).digest()
    h = base64.b64encode(digest).decode('utf-8')
    h = h.rstrip().rstrip('=')  # drop newline and possible base64 padding
    return 'SHA256:' + h
88036
def to_ipv6(key):
    """"""

    if key[-2:] != '.k':
        raise ValueError('Key does not end with .k')

    key_bytes = base32.decode(key[:-2])
    hash_one = sha512(key_bytes).digest()
    hash_two = sha512(hash_one).hexdigest()

    return ':'.join([hash_two[i:i+4] for i in range(0, 32, 4)])
1350054
def generate_request_access_signature(parameters, secret_key):
    
    # pull out the parameter keys
    keys = parameters.keys()

    # alphanumerically sort the keys in place
    keys.sort()

    # create an array of url encoded key:value pairs
    encoded_pairs = [urlencode({key: parameters[key]}) for key in keys]

    # create the serialized parameters in a single, URL style string
    serialized_parameters = '&'.join(encoded_pairs)

    # create the string with the secret key and the parameters which will be hashed
    string_to_hash = '%s:%s' % (secret_key, serialized_parameters)

    # return the hex digest of the hashed string
    return sha256(string_to_hash).hexdigest()
578379
async def get_ssh_key(self, raw_ssh=False):
        
        key_facade = client.KeyManagerFacade.from_connection(self.connection())
        entity = {'tag': tag.model(self.info.uuid)}
        entities = client.Entities([entity])
        return await key_facade.ListKeys(entities, raw_ssh)
909783
def Sign(verifiable, keypair):
        
        prikey = bytes(keypair.PrivateKey)
        hashdata = verifiable.GetHashData()
        res = Crypto.Default().Sign(hashdata, prikey)
        return res
370346
def key(self, user="", areq=None):
        
        csum = hashlib.new('sha224')
        csum.update(rndstr(32).encode('utf-8'))
        return csum.hexdigest()
85549
def get_fingerprint(self, fs):
        
        hasher = hashlib.md5()
        # we encode the content to avoid python 3 uncicode errors
        buf = self._encode_data(fs.read(self.BLOCK_SIZE))
        while len(buf) > 0:
            hasher.update(buf)
            buf = fs.read(self.BLOCK_SIZE)
        return 'md5:' + hasher.hexdigest()
309370
def sign(key)
      raise InvalidTransaction, "Zero privkey cannot sign" if [0, '', Constant::PRIVKEY_ZERO, Constant::PRIVKEY_ZERO_HEX].include?(key)

      rawhash = Utils.keccak256 signing_data(:sign)
      key = PrivateKey.new(key).encode(:bin)

      vrs = Secp256k1.recoverable_sign rawhash, key
      self.v = encode_v(vrs[0])
      self.r = vrs[1]
      self.s = vrs[2]

      self.sender = PrivateKey.new(key).to_address

      self
    end
718649
async def remove_ssh_key(self, user, key):
        
        key_facade = client.KeyManagerFacade.from_connection(self.connection())
        key = base64.b64decode(bytes(key.strip().split()[1].encode('ascii')))
        key = hashlib.md5(key).hexdigest()
        key = ':'.join(a + b for a, b in zip(key[::2], key[1::2]))
        await key_facade.DeleteKeys([key], user)
1266376
def sign(self, encoded):
        
        signature = self._hmac.copy()
        signature.update(encoded)
        return signature.hexdigest().encode('utf-8')
596166
async def do_authentication(sender):
    
    # Step 1 sending: PQ Request, endianness doesn't matter since it's random
    nonce = int.from_bytes(os.urandom(16), 'big', signed=True)
    res_pq = await sender.send(ReqPqMultiRequest(nonce))
    assert isinstance(res_pq, ResPQ), 'Step 1 answer was %s' % res_pq

    if res_pq.nonce != nonce:
        raise SecurityError('Step 1 invalid nonce from server')

    pq = get_int(res_pq.pq)

    # Step 2 sending: DH Exchange
    p, q = Factorization.factorize(pq)
    p, q = rsa.get_byte_array(p), rsa.get_byte_array(q)
    new_nonce = int.from_bytes(os.urandom(32), 'little', signed=True)

    pq_inner_data = bytes(PQInnerData(
        pq=rsa.get_byte_array(pq), p=p, q=q,
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        new_nonce=new_nonce
    ))

    # sha_digest + data + random_bytes
    cipher_text, target_fingerprint = None, None
    for fingerprint in res_pq.server_public_key_fingerprints:
        cipher_text = rsa.encrypt(fingerprint, pq_inner_data)
        if cipher_text is not None:
            target_fingerprint = fingerprint
            break

    if cipher_text is None:
        raise SecurityError(
            'Step 2 could not find a valid key for fingerprints: {}'
            .format(', '.join(
                [str(f) for f in res_pq.server_public_key_fingerprints])
            )
        )

    server_dh_params = await sender.send(ReqDHParamsRequest(
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        p=p, q=q,
        public_key_fingerprint=target_fingerprint,
        encrypted_data=cipher_text
    ))

    assert isinstance(
        server_dh_params, (ServerDHParamsOk, ServerDHParamsFail)),\
        'Step 2.1 answer was %s' % server_dh_params

    if server_dh_params.nonce != res_pq.nonce:
        raise SecurityError('Step 2 invalid nonce from server')

    if server_dh_params.server_nonce != res_pq.server_nonce:
        raise SecurityError('Step 2 invalid server nonce from server')

    if isinstance(server_dh_params, ServerDHParamsFail):
        nnh = int.from_bytes(
            sha1(new_nonce.to_bytes(32, 'little', signed=True)).digest()[4:20],
            'little', signed=True
        )
        if server_dh_params.new_nonce_hash != nnh:
            raise SecurityError('Step 2 invalid DH fail nonce from server')

    assert isinstance(server_dh_params, ServerDHParamsOk),\
        'Step 2.2 answer was %s' % server_dh_params

    # Step 3 sending: Complete DH Exchange
    key, iv = helpers.generate_key_data_from_nonce(
        res_pq.server_nonce, new_nonce
    )
    if len(server_dh_params.encrypted_answer) % 16 != 0:
        # See PR#453
        raise SecurityError('Step 3 AES block size mismatch')

    plain_text_answer = AES.decrypt_ige(
        server_dh_params.encrypted_answer, key, iv
    )

    with BinaryReader(plain_text_answer) as reader:
        reader.read(20)  # hash sum
        server_dh_inner = reader.tgread_object()
        assert isinstance(server_dh_inner, ServerDHInnerData),\
            'Step 3 answer was %s' % server_dh_inner

    if server_dh_inner.nonce != res_pq.nonce:
        raise SecurityError('Step 3 Invalid nonce in encrypted answer')

    if server_dh_inner.server_nonce != res_pq.server_nonce:
        raise SecurityError('Step 3 Invalid server nonce in encrypted answer')

    dh_prime = get_int(server_dh_inner.dh_prime, signed=False)
    g_a = get_int(server_dh_inner.g_a, signed=False)
    time_offset = server_dh_inner.server_time - int(time.time())

    b = get_int(os.urandom(256), signed=False)
    gb = pow(server_dh_inner.g, b, dh_prime)
    gab = pow(g_a, b, dh_prime)

    # Prepare client DH Inner Data
    client_dh_inner = bytes(ClientDHInnerData(
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        retry_id=0,  # TODO Actual retry ID
        g_b=rsa.get_byte_array(gb)
    ))

    client_dh_inner_hashed = sha1(client_dh_inner).digest() + client_dh_inner

    # Encryption
    client_dh_encrypted = AES.encrypt_ige(client_dh_inner_hashed, key, iv)

    # Prepare Set client DH params
    dh_gen = await sender.send(SetClientDHParamsRequest(
        nonce=res_pq.nonce,
        server_nonce=res_pq.server_nonce,
        encrypted_data=client_dh_encrypted,
    ))

    nonce_types = (DhGenOk, DhGenRetry, DhGenFail)
    assert isinstance(dh_gen, nonce_types), 'Step 3.1 answer was %s' % dh_gen
    name = dh_gen.__class__.__name__
    if dh_gen.nonce != res_pq.nonce:
        raise SecurityError('Step 3 invalid {} nonce from server'.format(name))

    if dh_gen.server_nonce != res_pq.server_nonce:
        raise SecurityError(
            'Step 3 invalid {} server nonce from server'.format(name))

    auth_key = AuthKey(rsa.get_byte_array(gab))
    nonce_number = 1 + nonce_types.index(type(dh_gen))
    new_nonce_hash = auth_key.calc_new_nonce_hash(new_nonce, nonce_number)

    dh_hash = getattr(dh_gen, 'new_nonce_hash{}'.format(nonce_number))
    if dh_hash != new_nonce_hash:
        raise SecurityError('Step 3 invalid new nonce hash')

    if not isinstance(dh_gen, DhGenOk):
        raise AssertionError('Step 3.2 answer was %s' % dh_gen)

    return auth_key, time_offset
635901
def sha256(message, encoder=nacl.encoding.HexEncoder):
    
    return encoder.encode(nacl.bindings.crypto_hash_sha256(message))
1234513
def sign(self, method, params):
        
        query_str = utils.percent_encode(params.items(), True)

        str_to_sign = "{0}&%2F&{1}".format(
            method, utils.percent_quote(query_str)
        )

        sig = hmac.new(
            utils.to_bytes(self._secret_key + "&"),
            utils.to_bytes(str_to_sign),
            hashlib.sha1
        )
        return base64.b64encode(sig.digest())
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()
        )
1351349
def _key_digest(self, secret_key):
        
        '''
            
        '''
        
        from hashlib import md5, sha256
        from base64 import b64encode
        key_bytes = sha256(secret_key.encode('utf-8')).digest()
        key_b64 = b64encode(key_bytes).decode()
        digest_bytes = md5(key_bytes).digest()
        digest_b64 = b64encode(digest_bytes).decode()
        
        return key_b64, digest_b64
1028042
def key_pair(i, region):
    """"""
    if i == 0:
        return ("{}_{}".format(RAY, region),
                os.path.expanduser("~/.ssh/{}_{}.pem".format(RAY, region)))
    return ("{}_{}_{}".format(RAY, i, region),
            os.path.expanduser("~/.ssh/{}_{}_{}.pem".format(RAY, i, region)))
816995
def compressedpubkey(self):
        
        secret = unhexlify(repr(self._wif))
        order = ecdsa.SigningKey.from_string(
            secret, curve=ecdsa.SECP256k1).curve.generator.order()
        p = ecdsa.SigningKey.from_string(
            secret, curve=ecdsa.SECP256k1).verifying_key.pubkey.point
        x_str = ecdsa.util.number_to_string(p.x(), order)
        y_str = ecdsa.util.number_to_string(p.y(), order)
        compressed = hexlify(
            chr(2 + (p.y() & 1)).encode('ascii') + x_str
        ).decode('ascii')
        uncompressed = hexlify(
            chr(4).encode('ascii') + x_str + y_str).decode(
            'ascii')
        return [compressed, uncompressed]