Given a digest and a private key, sign it.
    Return the base64-encoded signature
185256
def sign_digest(hash_hex, privkey_hex, hashfunc=hashlib.sha256):
    
    if not isinstance(hash_hex, (str, unicode)):
        raise ValueError("hash hex is not a string")

    hash_hex = str(hash_hex)

    pk_i = decode_privkey_hex(privkey_hex)
    privk = ec.derive_private_key(pk_i, ec.SECP256K1(), default_backend())

    sig = privk.sign(hash_hex.decode('hex'), ec.ECDSA(utils.Prehashed(hashes.SHA256())))

    sig_r, sig_s = decode_dss_signature(sig)
    sigb64 = encode_signature(sig_r, sig_s)
    return sigb64
881665
def sign_digest(sock, keygrip, digest, sp=subprocess, environ=None):
    """"""
    hash_algo = 8  # SHA256
    assert len(digest) == 32

    assert communicate(sock, 'RESET').startswith(b'OK')

    ttyname = check_output(args=['tty'], sp=sp).strip()
    options = ['ttyname={}'.format(ttyname)]  # set TTY for passphrase entry

    display = (environ or os.environ).get('DISPLAY')
    if display is not None:
        options.append('display={}'.format(display))

    for opt in options:
        assert communicate(sock, 'OPTION {}'.format(opt)) == b'OK'

    assert communicate(sock, 'SIGKEY {}'.format(keygrip)) == b'OK'
    hex_digest = binascii.hexlify(digest).upper().decode('ascii')
    assert communicate(sock, 'SETHASH {} {}'.format(hash_algo,
                                                    hex_digest)) == b'OK'

    assert communicate(sock, 'SETKEYDESC '
                       'Sign+a+new+TREZOR-based+subkey') == b'OK'
    assert communicate(sock, 'PKSIGN') == b'OK'
    while True:
        line = recvline(sock).strip()
        if line.startswith(b'S PROGRESS'):
            continue
        else:
            break
    line = unescape(line)
    log.debug('unescaped: %r', line)
    prefix, sig = line.split(b' ', 1)
    if prefix != b'D':
        raise ValueError(prefix)

    sig, leftover = parse(sig)
    assert not leftover, leftover
    return parse_sig(sig)
1176028
def sign_message(self, key, message, verbose=False):
        
        secret_exponent = key.secret_exponent()
        if not secret_exponent:
            raise ValueError("Private key is required to sign a message")

        addr = key.address()

        msg_hash = self.hash_for_signing(message)
        is_compressed = key.is_compressed()

        sig = self.signature_for_message_hash(secret_exponent, msg_hash, is_compressed)

        if not verbose or message is None:
            return sig

        return self.signature_template.format(
            msg=message, sig=sig, addr=addr,
            net_name=self._network_name.upper())
728675
def digest_password
      token = nonce + timestamp + password
      Base64.encode64(Digest::SHA1.digest(token)).chomp!
    end
585050
public function signature ( $request, $base_string, $consumer_secret, $token_secret )
	{
		// Fetch the private key cert based on the request
		$cert = $this->fetch_private_cert($request);
		
		// Pull the private key ID from the certificate
		$privatekeyid = openssl_get_privatekey($cert);
		
		// Sign using the key
		$sig = false;
		$ok  = openssl_sign($base_string, $sig, $privatekeyid);   
		
		// Release the key resource
		openssl_free_key($privatekeyid);
		  
		return $request->urlencode(base64_encode($sig));
	}
1141174
def sign(self, message):
		
		return hmac.HMAC(self.key, message, digestmod=hashlib.md5).digest()
161006
def make_signature(params, hmac_key):
    
    # produce a list of "key=value" for all entries in params except `h'
    pairs = [x + "=" + ''.join(params[x]) for x in sorted(params.keys()) if x != "h"]
    sha = hmac.new(hmac_key, '&'.join(pairs), hashlib.sha1)
    return base64.b64encode(sha.digest())
1167825
def crypto_sign(msg, sk):
    """"""
    if len(sk) != SECRETKEYBYTES:
        raise ValueError("Bad signing key length %d" % len(sk))
    vkbytes = sk[PUBLICKEYBYTES:]
    skbytes = sk[:PUBLICKEYBYTES]
    sig = djbec.signature(msg, skbytes, vkbytes)
    return sig + msg
1169252
def verify_digest(hash_hex, pubkey_hex, sigb64, hashfunc=hashlib.sha256):
    
    if not isinstance(hash_hex, (str, unicode)):
        raise ValueError("hash hex is not a string")

    hash_hex = str(hash_hex)
    pubk_uncompressed_hex = keylib.key_formatting.decompress(pubkey_hex)
    sig_r, sig_s = decode_signature(sigb64)

    pubk = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256K1(), pubk_uncompressed_hex.decode('hex')).public_key(default_backend())
    signature = encode_dss_signature(sig_r, sig_s)

    try:
        pubk.verify(signature, hash_hex.decode('hex'), ec.ECDSA(utils.Prehashed(hashes.SHA256())))
        return True
    except InvalidSignature:
        return False
1069526
def sign_with_privkey(
    digest: bytes,
    privkey: Ed25519PrivateKey,
    global_pubkey: Ed25519PublicPoint,
    nonce: int,
    global_commit: Ed25519PublicPoint,
) -> Ed25519Signature:
    
    h = _ed25519.H(privkey)
    a = _ed25519.decodecoord(h)

    S = (nonce + _ed25519.Hint(global_commit + global_pubkey + digest) * a) % _ed25519.l
    return Ed25519Signature(_ed25519.encodeint(S))
648798
def sign_request(private_key, method, endpoint, body_bytes, headers):
    

    head_bytes = _generate_request_head_bytes(method, endpoint, headers)
    bytes_to_sign = head_bytes + body_bytes
    signer = PKCS1_v1_5.new(private_key)
    digest = SHA256.new()
    digest.update(bytes_to_sign)
    sign = signer.sign(digest)

    return b64encode(sign)
683786
def sign(s, passphrase, sig_format=SER_COMPACT, curve='secp160r1'):
    
    if isinstance(s, six.text_type):
        raise ValueError("Encode `s` to a bytestring yourself to" +
                         " prevent problems with different default encodings")
    curve = Curve.by_name(curve)
    privkey = curve.passphrase_to_privkey(passphrase)
    return privkey.sign(hashlib.sha512(s).digest(), sig_format)
578136
def sign(jwk, plain_text, header = nil)
      protected_binary = JOSE.urlsafe_encode64(to_binary)
      payload = JOSE.urlsafe_encode64(plain_text)
      signing_input = signing_input(plain_text, protected_binary)
      signature = JOSE.urlsafe_encode64(alg.sign(jwk, signing_input))
      return signature_to_map(payload, protected_binary, header, jwk, signature)
    end
706835
def derive_signature(key, qs):
    """"""
    key, qs = (key or "", qs or "")
    return hmac.new(key.encode(), qs.encode(), hashlib.sha1).hexdigest()
1028143
def generate_signature(method, version, endpoint,
                       date, rel_url, content_type, content,
                       access_key, secret_key, hash_type):
    '''
    
    '''
    hash_type = hash_type
    hostname = endpoint._val.netloc  # FIXME: migrate to public API
    if version >= 'v4.20181215':
        content = b''
    else:
        if content_type.startswith('multipart/'):
            content = b''
    body_hash = hashlib.new(hash_type, content).hexdigest()

    sign_str = '{}\n{}\n{}\nhost:{}\ncontent-type:{}\nx-backendai-version:{}\n{}'.format(  # noqa
        method.upper(),
        rel_url,
        date.isoformat(),
        hostname,
        content_type.lower(),
        version,
        body_hash
    )
    sign_bytes = sign_str.encode()

    sign_key = hmac.new(secret_key.encode(),
                        date.strftime('%Y%m%d').encode(), hash_type).digest()
    sign_key = hmac.new(sign_key, hostname.encode(), hash_type).digest()

    signature = hmac.new(sign_key, sign_bytes, hash_type).hexdigest()
    headers = {
        'Authorization': 'BackendAI signMethod=HMAC-{}, credential={}:{}'.format(
            hash_type.upper(),
            access_key,
            signature
        ),
    }
    return headers, signature
489058
def sign_raw_data(raw_data, privatekey_hex):
    
    if not isinstance(raw_data, (str, unicode)):
        raise ValueError("Data is not a string")

    raw_data = str(raw_data)

    si = ECSigner(privatekey_hex)
    si.update(raw_data)
    return si.finalize()
777193
def signing_base(self, request, consumer, token):
        """"""
        sig = '%s&' % escape(consumer.secret)
        if token:
            sig = sig + escape(token.secret)
        return sig, sig