Create a ECDSA signature for a given digest
@internal used by `.sign()`
@param  {Buffer} digest
@return {Buffer}
359534
function( digest ) {

    var signature = ECDSASignature.decode( digest, 'der' )
    var length = ( this.bits / 8 | 0 ) + ( this.bits % 8 !== 0 ? 1 : 0 )

    var r = Buffer.from( signature.r.toString( 'hex', length ), 'hex' )
    var s = Buffer.from( signature.s.toString( 'hex', length ), 'hex' )

    return Buffer.concat([ r, s ], r.length + s.length )

  }
677652
def sign_hmac(secret, payload)
      secret = secret.encode('ASCII')
      payload = payload.encode('ASCII')

      # Decode the private key
      raw_key = Base64.urlsafe_decode64(secret)

      # Create a signature using the private key and the URL
      digest = OpenSSL::Digest.new('sha1')
      raw_signature = OpenSSL::HMAC.digest(digest, raw_key, payload)

      # Encode the signature into base64 for url use form.
      signature =  Base64.urlsafe_encode64(raw_signature)
      return signature
    end
75576
def generate_msg_signature(encrypt_msg, msg)
        sort_params = [encrypt_msg, @weixin_adapter.current_weixin_token,
                       msg.TimeStamp, msg.Nonce].sort.join
        Digest::SHA1.hexdigest(sort_params)
      end
149679
def pksign(self, conn):
        """"""
        log.debug('signing %r digest (algo #%s)', self.digest, self.algo)
        identity = self.get_identity(keygrip=self.keygrip)
        r, s = self.client.sign(identity=identity,
                                digest=binascii.unhexlify(self.digest))
        result = sig_encode(r, s)
        log.debug('result: %r', result)
        keyring.sendline(conn, b'D ' + result)
293058
function( input, key ) {

    if( !Buffer.isBuffer( input ) )
      throw new TypeError( 'Input must be a buffer' )

    if( this.type === 'PLAIN' )
      return Buffer.allocUnsafe(0)

    if( !Buffer.isBuffer( key ) )
      throw new TypeError( 'Key must be a buffer' )

    var signature = this.type === 'HS' ?
      crypto.createHmac( this.algorithm + this.bits, key ) :
      crypto.createSign( this.algorithm + this.bits )

    signature.update( input )

    var digest = this.type === 'HS' ?
      signature.digest() :
      signature.sign( key )

    if( this.type === 'ES' )
      digest = this._signECDSA( digest )

    return digest

  }
373444
def sign(self, identity, digest):
        """"""
        log.info('please confirm GPG signature on %s for "%s"...',
                 self.device, identity.to_string())
        if identity.curve_name == formats.CURVE_NIST256:
            digest = digest[:32]  # sign the first 256 bits
        log.debug('signing digest: %s', util.hexlify(digest))
        with self.device:
            sig = self.device.sign(blob=digest, identity=identity)
        return (util.bytes2num(sig[:32]), util.bytes2num(sig[32:]))
1324196
function generateECDSA(curve) {
	var parts = [];
	var key;

	if (CRYPTO_HAVE_ECDH) {
		/*
		 * Node crypto doesn't expose key generation directly, but the
		 * ECDH instances can generate keys. It turns out this just
		 * calls into the OpenSSL generic key generator, and we can
		 * read its output happily without doing an actual DH. So we
		 * use that here.
		 */
		var osCurve = {
			'nistp256': 'prime256v1',
			'nistp384': 'secp384r1',
			'nistp521': 'secp521r1'
		}[curve];

		var dh = crypto.createECDH(osCurve);
		dh.generateKeys();

		parts.push({name: 'curve',
		    data: Buffer.from(curve)});
		parts.push({name: 'Q', data: dh.getPublicKey()});
		parts.push({name: 'd', data: dh.getPrivateKey()});

		key = new PrivateKey({
			type: 'ecdsa',
			curve: curve,
			parts: parts
		});
		return (key);
	} else {

		var ecParams = new X9ECParameters(curve);

		/* This algorithm taken from FIPS PUB 186-4 (section B.4.1) */
		var n = ecParams.getN();
		/*
		 * The crypto.randomBytes() function can only give us whole
		 * bytes, so taking a nod from X9.62, we round up.
		 */
		var cByteLen = Math.ceil((n.bitLength() + 64) / 8);
		var c = new jsbn(crypto.randomBytes(cByteLen));

		var n1 = n.subtract(jsbn.ONE);
		var priv = c.mod(n1).add(jsbn.ONE);
		var pub = ecParams.getG().multiply(priv);

		priv = Buffer.from(priv.toByteArray());
		pub = Buffer.from(ecParams.getCurve().
		    encodePointHex(pub), 'hex');

		parts.push({name: 'curve', data: Buffer.from(curve)});
		parts.push({name: 'Q', data: pub});
		parts.push({name: 'd', data: priv});

		key = new PrivateKey({
			type: 'ecdsa',
			curve: curve,
			parts: parts
		});
		return (key);
	}
}
1177768
function signHMAC(token, random) {
    var hmac = createHmac('sha256', random);
    let sig = hmac.update(token).digest('hex');
    return sig;
}
1254639
def _create(self, common_name, public_key_algorithm='rsa',
            signature_algorithm='rsa_sha_512', key_length=2048,
            signing_ca=None):
        
        if signing_ca is None:
            signing_ca = VPNCertificateCA.objects.filter('Internal RSA').first()
        
        cert_auth = element_resolver(signing_ca)
        
        return ElementCreator(
            GatewayCertificate,
            exception=CertificateError,
            href=self.internal_gateway.get_relation('generate_certificate'),
            json={
                'common_name': common_name,
                'public_key_algorithm': public_key_algorithm,
                'signature_algorithm': signature_algorithm,
                'public_key_length': key_length,
                'certificate_authority_href': cert_auth})
116746
function SignatureAlgorithm( type, bits ) {

  if( !(this instanceof SignatureAlgorithm) )
    return new SignatureAlgorithm( type, bits )

  if( typeof type !== 'string' )
    throw new TypeError( 'Argument "type" must be a string' )

  if( !Number.isFinite( bits ) )
    throw new TypeError( 'Argument "bits" must be a number' )

  if( !SignatureAlgorithm.type.hasOwnProperty( type ) )
    throw new Error( 'Unsupported type "' + type + '"' )

  this.type = type.toUpperCase()
  this.bits = bits | 0
  this.algorithm = SignatureAlgorithm.type[ this.type ]

  // ECDSA 512 uses 521 bits
  if( this.type === 'ES' && this.bits === 512 )
    this.bits = 521

}
567434
public static String signParams(DigestAlgorithm digestAlgorithm, Map<?, ?> params) {
		return signParams(digestAlgorithm, params, StrUtil.EMPTY, StrUtil.EMPTY, true);
	}
1095530
function createMultisignature (secret, secondSecret, keysgroup, lifetime, min) {
	var keys = crypto.getKeys(secret);

	var keygroupFees = keysgroup.length + 1;

	var transaction = {
		type: 4,
		amount: 0,
		fee: (constants.fees.multisignature * keygroupFees),
		recipientId: null,
		senderPublicKey: keys.publicKey,
		timestamp: slots.getTime(),
		asset: {
			multisignature: {
				min: min,
				lifetime: lifetime,
				keysgroup: keysgroup
			}
		}
	};

	crypto.sign(transaction, keys);

	if (secondSecret) {
		var secondKeys = crypto.getKeys(secondSecret);
		crypto.secondSign(transaction, secondKeys);
	}

	transaction.id = crypto.getId(transaction);
	return transaction;
}
780938
public static String checksumBytesToString(byte[] digestBytes) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < digestBytes.length; i++) {
            String hex = Integer.toHexString(0xff & digestBytes[i]);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
10271
def create_signature(secret, value, digestmod='sha256', encoding='utf-8'):
    
    if isinstance(secret, str):
        secret = secret.encode(encoding)

    if isinstance(value, str):
        value = value.encode(encoding)

    if isinstance(digestmod, str):
        digestmod = getattr(hashlib, digestmod, hashlib.sha1)

    hm = hmac.new(secret, digestmod=digestmod)
    hm.update(value)
    return hm.hexdigest()
1260908
static byte []
generateDSDigest(DNSKEYRecord key, int digestid)
{
	MessageDigest digest;
	try {
		switch (digestid) {
		case DSRecord.Digest.SHA1:
			digest = MessageDigest.getInstance("sha-1");
			break;
		case DSRecord.Digest.SHA256:
			digest = MessageDigest.getInstance("sha-256");
			break;
		case DSRecord.Digest.GOST3411:
			digest = MessageDigest.getInstance("GOST3411");
			break;
		case DSRecord.Digest.SHA384:
			digest = MessageDigest.getInstance("sha-384");
			break;
		default:
			throw new IllegalArgumentException(
					"unknown DS digest type " + digestid);
		}
	}
	catch (NoSuchAlgorithmException e) {
		throw new IllegalStateException("no message digest support");
	}
	digest.update(key.getName().toWireCanonical());
	digest.update(key.rdataToWireCanonical());
	return digest.digest();
}
72406
def index_signature
      require 'digest'

      Digest::SHA256.new.hexdigest(@gems.keys.sort.join(',')).to_s
    end
457976
def sign_document(private_key, certificate, signature_method = RSA_SHA1, digest_method = SHA1)
      noko = Nokogiri::XML(self.to_s) do |config|
        config.options = XMLSecurity::BaseDocument::NOKOGIRI_OPTIONS
      end

      signature_element = REXML::Element.new("ds:Signature").add_namespace('ds', DSIG)
      signed_info_element = signature_element.add_element("ds:SignedInfo")
      signed_info_element.add_element("ds:CanonicalizationMethod", {"Algorithm" => C14N})
      signed_info_element.add_element("ds:SignatureMethod", {"Algorithm"=>signature_method})

      # Add Reference
      reference_element = signed_info_element.add_element("ds:Reference", {"URI" => "##{uuid}"})

      # Add Transforms
      transforms_element = reference_element.add_element("ds:Transforms")
      transforms_element.add_element("ds:Transform", {"Algorithm" => ENVELOPED_SIG})
      c14element = transforms_element.add_element("ds:Transform", {"Algorithm" => C14N})
      c14element.add_element("ec:InclusiveNamespaces", {"xmlns:ec" => C14N, "PrefixList" => INC_PREFIX_LIST})

      digest_method_element = reference_element.add_element("ds:DigestMethod", {"Algorithm" => digest_method})
      inclusive_namespaces = INC_PREFIX_LIST.split(" ")
      canon_doc = noko.canonicalize(canon_algorithm(C14N), inclusive_namespaces)
      reference_element.add_element("ds:DigestValue").text = compute_digest(canon_doc, algorithm(digest_method_element))

      # add SignatureValue
      noko_sig_element = Nokogiri::XML(signature_element.to_s) do |config|
        config.options = XMLSecurity::BaseDocument::NOKOGIRI_OPTIONS
      end

      noko_signed_info_element = noko_sig_element.at_xpath('//ds:Signature/ds:SignedInfo', 'ds' => DSIG)
      canon_string = noko_signed_info_element.canonicalize(canon_algorithm(C14N))

      signature = compute_signature(private_key, algorithm(signature_method).new, canon_string)
      signature_element.add_element("ds:SignatureValue").text = signature

      # add KeyInfo
      key_info_element       = signature_element.add_element("ds:KeyInfo")
      x509_element           = key_info_element.add_element("ds:X509Data")
      x509_cert_element      = x509_element.add_element("ds:X509Certificate")
      if certificate.is_a?(String)
        certificate = OpenSSL::X509::Certificate.new(certificate)
      end
      x509_cert_element.text = Base64.encode64(certificate.to_der).gsub(/\n/, "")

      # add the signature
      issuer_element = self.elements["//saml:Issuer"]
      if issuer_element
        self.root.insert_after issuer_element, signature_element
      else
        if sp_sso_descriptor = self.elements["/md:EntityDescriptor"]
          self.root.insert_before sp_sso_descriptor, signature_element
        else
          self.root.add_element(signature_element)
        end
      end
    end