## Transaction Signing  This function shows how to use a compliant private key to sign an æternity transaction and turn it into an RLP-encoded tuple ready for mining
11372
function signTx (tx, privKey) {
  if (!tx.match(/^tx\_.+/)) {
    throw Error('Not a valid transaction')
  }

  const binaryKey = (() => {
    if (program.file) {
      return fs.readFileSync(program.file)
    } else if (privKey) {
      return Buffer.from(privKey, 'hex')
    } else {
      throw Error('Must provide either [privkey] or [file]')
    }
  })()

  const decryptedKey = program.password ? Crypto.decryptKey(program.password, binaryKey) : binaryKey

  // Split the base58Check part of the transaction
  const base58CheckTx = tx.split('_')[1]
  // ... and sign the binary create_contract transaction
  const binaryTx = Crypto.decodeBase58Check(base58CheckTx)

  const signature = Crypto.sign(binaryTx, decryptedKey)

  // the signed tx deserializer expects a 4-tuple:
  // <tag, version, signatures_array, binary_tx>
  const unpackedSignedTx = [
    Buffer.from([11]),
    Buffer.from([1]),
    [Buffer.from(signature)],
    binaryTx
  ]

  console.log(Crypto.encodeTx(unpackedSignedTx))
}
56793
def embed_data_in_blockchain(data, private_key,
        blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE,
        change_address=None, format='bin'):
    
    # build and sign the tx
    signed_tx = make_op_return_tx(data, private_key, blockchain_client,
        fee=fee, change_address=change_address, format=format)
    # dispatch the signed transction to the network
    response = broadcast_transaction(signed_tx, blockchain_client)
    # return the response
    return response
111194
def sign_message(privkey_path, message, passphrase=None):
    '''
    
    '''
    key = get_rsa_key(privkey_path, passphrase)
    log.debug('salt.crypt.sign_message: Signing message.')
    if HAS_M2:
        md = EVP.MessageDigest('sha1')
        md.update(salt.utils.stringutils.to_bytes(message))
        digest = md.final()
        return key.sign(digest)
    else:
        signer = PKCS1_v1_5.new(key)
        return signer.sign(SHA.new(salt.utils.stringutils.to_bytes(message)))
196224
function ECKeySign(hashBytes, priKeyBytes) {
  let ec = new EC('secp256k1');
  let key = ec.keyFromPrivate(priKeyBytes, 'bytes');
  let signature = key.sign(hashBytes);
  let r = signature.r;
  let s = signature.s;
  let id = signature.recoveryParam;
  let rHex = r.toString('hex');
  while (rHex.length < 64) {
    rHex = "0" + rHex;
  }
  let sHex = s.toString('hex');
  while (sHex.length < 64) {
    sHex = "0" + sHex;
  }
  let idHex = byte2hexStr(id);
  let signHex = rHex + sHex + idHex;
  return hexStr2byteArray(signHex);
}
279922
def sign(self, digest, **kwargs):
        
        ctx = libcrypto.EVP_PKEY_CTX_new(self.key, None)
        if ctx is None:
            raise PKeyError("Initailizing sign context")
        if libcrypto.EVP_PKEY_sign_init(ctx) < 1:
            raise PKeyError("sign_init")
        self._configure_context(ctx, kwargs)
        # Find out signature size
        siglen = c_long(0)
        if libcrypto.EVP_PKEY_sign(ctx, None, byref(siglen), digest,
                                   len(digest)) < 1:
            raise PKeyError("computing signature length")
        sig = create_string_buffer(siglen.value)
        if libcrypto.EVP_PKEY_sign(ctx, sig, byref(siglen), digest,
                                   len(digest)) < 1:
            raise PKeyError("signing")
        libcrypto.EVP_PKEY_CTX_free(ctx)
        return sig.raw[:int(siglen.value)]
904254
function secondSign (transaction, keys) {
	var hash = getHash(transaction);
	var signature = naclInstance.crypto_sign_detached(hash, Buffer.from(keys.privateKey, 'hex'));
	transaction.signSignature = Buffer.from(signature).toString('hex');
}
189524
def seal(token, context = nil)
      raise RuntimeError, "signing private key must be set" unless self.instance_variable_get(:@signing_private_key)
      binary_token = token.to_binary_s
      signature = self.encryptor.sign(binary_token, self.instance_variable_get(:@signing_private_key), self, context)
      Base64.strict_encode64([binary_token, signature].join)
    end
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
700074
def btc_tx_sign_multisig(tx, idx, redeem_script, private_keys, hashcode=SIGHASH_ALL):
    
    
    from .multisig import parse_multisig_redeemscript

    # sign in the right order.  map all possible public keys to their private key
    txobj = btc_tx_deserialize(str(tx))

    privs = {}
    for pk in private_keys:
        pubk = ecdsalib.ecdsa_private_key(pk).public_key().to_hex()

        compressed_pubkey = keylib.key_formatting.compress(pubk)
        uncompressed_pubkey = keylib.key_formatting.decompress(pubk)

        privs[compressed_pubkey] = pk
        privs[uncompressed_pubkey] = pk

    m, public_keys = parse_multisig_redeemscript(str(redeem_script))

    used_keys, sigs = [], []
    for public_key in public_keys:
        if public_key not in privs:
            continue

        if len(used_keys) == m:
            break

        if public_key in used_keys:
            raise ValueError('Tried to reuse key in redeem script: {}'.format(public_key))

        pk_str = privs[public_key]
        used_keys.append(public_key)

        sig = btc_tx_make_input_signature(tx, idx, redeem_script, pk_str, hashcode)
        sigs.append(sig)

    if len(used_keys) != m:
        raise ValueError('Missing private keys (used {}, required {})'.format(len(used_keys), m))

    txobj["ins"][idx]["script"] = btc_script_serialize([None] + sigs + [redeem_script])
    return btc_tx_serialize(txobj)
1366747
def sign(params)
      string = params_to_string(params)

      case @sign_type
      when 'RSA'
        ::Alipay::Sign::RSA.sign(@app_private_key, string)
      when 'RSA2'
        ::Alipay::Sign::RSA2.sign(@app_private_key, string)
      else
        raise "Unsupported sign_type: #{@sign_type}"
      end
    end
1300458
def crypto_sign_keypair():
    
    pk = ffi.new("unsigned char[]", crypto_sign_PUBLICKEYBYTES)
    sk = ffi.new("unsigned char[]", crypto_sign_SECRETKEYBYTES)

    rc = lib.crypto_sign_keypair(pk, sk)
    ensure(rc == 0,
           'Unexpected library error',
           raising=exc.RuntimeError)

    return (
        ffi.buffer(pk, crypto_sign_PUBLICKEYBYTES)[:],
        ffi.buffer(sk, crypto_sign_SECRETKEYBYTES)[:],
    )
733863
function signTransaction (trs, secret) {
	var keys = crypto.getKeys(secret);
	var signature = crypto.multiSign(trs, keys);

	return {
		transaction: trs.id,
		signature: signature
	};
}
647534
def signrawtransaction(self, rawtxhash, parent_tx_outputs=None, private_key=None):
        

        if not parent_tx_outputs and not private_key:
            return self.req("signrawtransaction", [rawtxhash])
        else:
            return self.req(
                "signrawtransaction", [rawtxhash, parent_tx_outputs, private_key]
            )
1264466
function verify (transaction) {
	var remove = 64;

	if (transaction.signSignature) {
		remove = 128;
	}

	var bytes = getBytes(transaction);
	var data2 = Buffer.alloc(bytes.length - remove);

	for (var i = 0; i < data2.length; i++) {
		data2[i] = bytes[i];
	}

	var hash = crypto.createHash('sha256').update(data2.toString('hex'), 'hex').digest();

	var signatureBuffer = Buffer.from(transaction.signature, 'hex');
	var senderPublicKeyBuffer = Buffer.from(transaction.senderPublicKey, 'hex');
	var res = naclInstance.crypto_sign_verify_detached(signatureBuffer, hash, senderPublicKeyBuffer);

	return res;
}
658263
def make_signature(signer_func, data_to_sign, public_algo,
                   hashed_subpackets, unhashed_subpackets, sig_type=0):
    """"""
    # pylint: disable=too-many-arguments
    header = struct.pack('>BBBB',
                         4,         # version
                         sig_type,  # rfc4880 (section-5.2.1)
                         public_algo,
                         8)         # hash_alg (SHA256)
    hashed = subpackets(*hashed_subpackets)
    unhashed = subpackets(*unhashed_subpackets)
    tail = b'\x04\xff' + struct.pack('>L', len(header) + len(hashed))
    data_to_hash = data_to_sign + header + hashed + tail

    log.debug('hashing %d bytes', len(data_to_hash))
    digest = hashlib.sha256(data_to_hash).digest()
    log.debug('signing digest: %s', util.hexlify(digest))
    params = signer_func(digest=digest)
    sig = b''.join(mpi(p) for p in params)

    return bytes(header + hashed + unhashed +
                 digest[:2] +  # used for decoder's sanity check
                 sig)
455040
function verifySecondSignature (transaction, publicKey) {
	var bytes = getBytes(transaction);
	var data2 = Buffer.alloc(bytes.length - 64);

	for (var i = 0; i < data2.length; i++) {
		data2[i] = bytes[i];
	}

	var hash = crypto.createHash('sha256').update(data2.toString('hex'), 'hex').digest();

	var signSignatureBuffer = Buffer.from(transaction.signSignature, 'hex');
	var publicKeyBuffer = Buffer.from(publicKey, 'hex');
	var res = naclInstance.crypto_sign_verify_detached(signSignatureBuffer, hash, publicKeyBuffer);

	return res;
}
421277
public ECDSASignature sign(byte[] transactionHash) {
        ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));

        ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKey, Sign.CURVE);
        signer.init(true, privKey);
        BigInteger[] components = signer.generateSignature(transactionHash);

        return new ECDSASignature(components[0], components[1]).toCanonicalised();
    }