Helper to send signed messages.

        This method will use the `privkey` provided in the constructor to
        locally sign the transaction. This requires an extended server
        implementation that accepts the variables v, r, and s.
334938
def send_transaction(
            self,
            to: Address,
            startgas: int,
            value: int = 0,
            data: bytes = b'',
    ) -> bytes:
        
        if to == to_canonical_address(constants.NULL_ADDRESS):
            warnings.warn('For contract creation the empty string must be used.')

        with self._nonce_lock:
            nonce = self._available_nonce
            gas_price = self.gas_price()

            transaction = {
                'data': data,
                'gas': startgas,
                'nonce': nonce,
                'value': value,
                'gasPrice': gas_price,
            }
            node_gas_price = self.web3.eth.gasPrice
            log.debug(
                'Calculated gas price for transaction',
                node=pex(self.address),
                calculated_gas_price=gas_price,
                node_gas_price=node_gas_price,
            )

            # add the to address if not deploying a contract
            if to != b'':
                transaction['to'] = to_checksum_address(to)

            signed_txn = self.web3.eth.account.signTransaction(transaction, self.privkey)

            log_details = {
                'node': pex(self.address),
                'nonce': transaction['nonce'],
                'gasLimit': transaction['gas'],
                'gasPrice': transaction['gasPrice'],
            }
            log.debug('send_raw_transaction called', **log_details)

            tx_hash = self.web3.eth.sendRawTransaction(signed_txn.rawTransaction)
            self._available_nonce += 1

            log.debug('send_raw_transaction returned', tx_hash=encode_hex(tx_hash), **log_details)
            return tx_hash
207365
def send_message(self, message, sign=True):
		
		if sign:
			message.sign(self.authenticators[self.defauth])
		logger.debug("sending %s", LazyStr(message.dump_oneline))
		self.transport.write(message.as_string())
116794
def sign_singlesig(privkey_hex, plaintext):
    
    hash_hex = hashlib.sha256(plaintext).hexdigest()
    b64sig = virtualchain.ecdsalib.sign_digest(hash_hex, privkey_hex)
    sighex = binascii.hexlify(base64.b64decode(b64sig))
    pubkey_hex = virtualchain.ecdsalib.ecdsa_private_key(privkey_hex).public_key().to_hex()
    return base64.b64encode(virtualchain.btc_script_serialize([sighex, pubkey_hex]).decode('hex'))
151433
public String sign(KeyStoreChooser keyStoreChooser, PrivateKeyChooserByAlias privateKeyChooserByAlias, String message) {
		Base64EncodedSigner signer = cache.get(cacheKey(keyStoreChooser, privateKeyChooserByAlias));

		if (signer != null) {
			return signer.sign(message);
		}

		Base64EncodedSignerImpl signerImpl = new Base64EncodedSignerImpl();
		signerImpl.setAlgorithm(algorithm);
		signerImpl.setCharsetName(charsetName);
		signerImpl.setProvider(provider);
		PrivateKey privateKey = privateKeyRegistryByAlias.get(keyStoreChooser, privateKeyChooserByAlias);

		if (privateKey == null) {
			throw new SignatureException("private key not found: keyStoreName=" + keyStoreChooser.getKeyStoreName()
					+ ", alias=" + privateKeyChooserByAlias.getAlias());
		}

		signerImpl.setPrivateKey(privateKey);
		cache.put(cacheKey(keyStoreChooser, privateKeyChooserByAlias), signerImpl);
		return signerImpl.sign(message);
	}
501370
function(signer) {
      if('content' in msg) {
        throw new Error('PKCS#7 signing not yet implemented.');
      }

      if(typeof msg.content !== 'object') {
        // use Data ContentInfo
        msg.contentInfo = asn1.create(
          asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
            // ContentType
            asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
              asn1.oidToDer(forge.pki.oids.data).getBytes())
          ]);

        // add actual content, if present
        if('content' in msg) {
          msg.contentInfo.value.push(
            // [0] EXPLICIT content
            asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
              asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
                msg.content)
            ]));
        }
      }

      // TODO: generate digest algorithm identifiers

      // TODO: generate signerInfos
    }
313143
def sign(payload, keypair):
    """"""
    get_ed25519ll()
    #
    header = {
                "alg": ALG,
                "jwk": {
                    "kty": ALG,  # alg -> kty in jwk-08.
                    "vk": native(urlsafe_b64encode(keypair.vk))
                }
             }

    encoded_header = urlsafe_b64encode(binary(json.dumps(header, sort_keys=True)))
    encoded_payload = urlsafe_b64encode(binary(json.dumps(payload, sort_keys=True)))
    secured_input = b".".join((encoded_header, encoded_payload))
    sig_msg = ed25519ll.crypto_sign(secured_input, keypair.sk)
    signature = sig_msg[:ed25519ll.SIGNATUREBYTES]
    encoded_signature = urlsafe_b64encode(signature)

    return {"recipients":
            [{"header": native(encoded_header),
              "signature": native(encoded_signature)}],
            "payload": native(encoded_payload)}
639031
def crypto_sign(message, sk):
    
    signed = ffi.new("unsigned char[]", len(message) + crypto_sign_BYTES)
    signed_len = ffi.new("unsigned long long *")

    rc = lib.crypto_sign(signed, signed_len, message, len(message), sk)
    ensure(rc == 0,
           'Unexpected library error',
           raising=exc.RuntimeError)

    return ffi.buffer(signed, signed_len[0])[:]
215261
function command (
  {
    privateKeys,
    creatorAccountId,
    quorum,
    commandService,
    timeoutLimit
  } = DEFAULT_OPTIONS,
  tx
) {
  let txToSend = txHelper.addMeta(tx, {
    creatorAccountId,
    quorum
  })

  txToSend = signWithArrayOfKeys(txToSend, privateKeys)

  let txClient = commandService

  return sendTransactions([txToSend], txClient, timeoutLimit)
}
471646
def sign(self, data, b64=True):
        
        padder = padding.PKCS1v15()
        signer = self.private_key.signer(padder, None)
        if not isinstance(data, six.binary_type):
            data = data.encode('utf_8')
        signer.update(data)
        signed = signer.finalize()
        if b64:
            signed = base64.b64encode(signed)
        return signed
799222
async def sign(self, message: bytes) -> bytes:
        

        LOGGER.debug('BaseAnchor.sign >>> message: %s', message)

        if not self.wallet.handle:
            LOGGER.debug('BaseAnchor.sign <!< Wallet %s is closed', self.name)
            raise WalletState('Wallet {} is closed'.format(self.name))

        rv = await self.wallet.sign(message)

        LOGGER.debug('BaseAnchor.sign <<< %s', rv)
        return rv
330758
def crypto_sign_open(signed, pk):
    
    message = ffi.new("unsigned char[]", len(signed))
    message_len = ffi.new("unsigned long long *")

    if lib.crypto_sign_open(
            message, message_len, signed, len(signed), pk) != 0:
        raise exc.BadSignatureError("Signature was forged or corrupt")

    return ffi.buffer(message, message_len[0])[:]
1005988
def btc_tx_make_input_signature_segwit(tx, idx, prevout_amount, prevout_script, privkey_str, hashcode):
    
    # always compressed
    if len(privkey_str) == 64:
        privkey_str += '01'

    pk = ecdsalib.ecdsa_private_key(str(privkey_str))
    pubk = pk.public_key()
    
    priv = pk.to_hex()

    # must always be compressed
    pub = keylib.key_formatting.compress(pubk.to_hex())
    sighash = btc_tx_sighash_segwit(tx, idx, prevout_amount, prevout_script, hashcode=hashcode)
    
    # sign using uncompressed private key
    # pk_uncompressed_hex, pubk_uncompressed_hex = ecdsalib.get_uncompressed_private_and_public_keys(priv)
    sigb64 = ecdsalib.sign_digest( sighash, priv )

    # sanity check 
    # assert ecdsalib.verify_digest( txhash, pubk_uncompressed_hex, sigb64 )

    sig_r, sig_s = ecdsalib.decode_signature(sigb64)
    sig_bin = btc_tx_der_encode_signature(sig_r, sig_s)
    sig = sig_bin.encode('hex') + encoding.encode(hashcode, 16, 2)

    # print 'segwit signature: {}'.format(sig)
    return sig
714929
def sign(message, gpg_home=None, gpg_signing_key=None, **config):
    

    if gpg_home is None or gpg_signing_key is None:
        raise ValueError("You must set the gpg_home \
                         and gpg_signing_key keyword arguments.")

    message['crypto'] = 'gpg'

    signature = _ctx.sign(
        fedmsg.encoding.dumps(message['msg']),
        gpg_signing_key,
        homedir=gpg_home
    )
    return dict(list(message.items()) + [('signature', b64encode(signature))])
551348
@Override
    public void sign ( byte[] data, int offset, int length, CommonServerMessageBlock request, CommonServerMessageBlock response ) {
        if ( log.isTraceEnabled() ) {
            log.trace("Signing with seq " + this.signSequence);
        }

        ( (ServerMessageBlock) request ).setSignSeq(this.signSequence);
        if ( response != null ) {
            ( (ServerMessageBlock) response ).setSignSeq(this.signSequence + 1);
        }

        try {
            update(this.macSigningKey, 0, this.macSigningKey.length);
            int index = offset + SmbConstants.SIGNATURE_OFFSET;
            for ( int i = 0; i < 8; i++ )
                data[ index + i ] = 0;
            SMBUtil.writeInt4(this.signSequence, data, index);
            update(data, offset, length);
            System.arraycopy(digest(), 0, data, index, 8);
            if ( this.bypass ) {
                this.bypass = false;
                System.arraycopy("BSRSPYL ".getBytes(), 0, data, index, 8);
            }
        }
        catch ( Exception ex ) {
            log.error("Signature failed", ex);
        }
        finally {
            if ( request instanceof SmbComNtCancel ) {
                this.signSequence++;
            }
            else {
                this.signSequence += 2;
            }
        }
    }
1292009
private void signP2SHInput(Transaction tx, Transaction.SigHash hashType,
                               boolean anyoneCanPay, @Nullable KeyParameter userKey) {
        TransactionSignature signature = tx.calculateSignature(0, serverKey, userKey, createP2SHRedeemScript(), hashType, anyoneCanPay);
        byte[] mySig = signature.encodeToBitcoin();
        Script scriptSig = ScriptBuilder.createCLTVPaymentChannelP2SHInput(bestValueSignature, mySig, createP2SHRedeemScript());
        tx.getInput(0).setScriptSig(scriptSig);
    }
112091
def sign(xml, private, public):
    '''
    
    '''
    xml = xml.encode('utf-8', 'xmlcharrefreplace')
    signed_info_xml = _generate_signed_info(xml)

    signer = PKCS1_v1_5.PKCS115_SigScheme(private)
    signature_value = signer.sign(SHA.new(c14n(signed_info_xml)))

    signature_xml = PTN_SIGNATURE_XML % {
        'signed_info_xml': signed_info_xml,
        'signature_value': binascii.b2a_base64(signature_value)[:-1],
        'key_info_xml': _generate_key_info_xml_rsa(public.key.n, public.key.e)
    }

    position = xml.rfind('</')
    return xml[0:position] + signature_xml + xml[position:]
752307
public static String sign(String content, String priKey) {
        return Base64Util.encode2String(RSA.sign(content.getBytes(), decryptPrivateKey(priKey)));
    }