/*
Signs a message z on the elliptic curve with paramater a in the finite field
of order p using the given private key d and generator point G having cyclic
order n, and stores the signature components in r and s.
172531
function ecp_sign(r, s, p, a, G, n, d, z, l) {
	var R = ecp_new(l), S = ecp_new(l), k = mpn_new(l);
	for (;;) {
		for (var i = 0; i < l; ++i) {
			k[i] = Math.random() * 0x80000000 | 0;
		}
		var r0 = ecp_proj(R, ecp_mul(S, k, G, a, p, l), p, l)[0];
		if (mpn_cmp(r0, n, l) >= 0) {
			mpn_sub(r0, r0, n, l);
		}
		if (!mpn_zero_p(r0, l)) {
			var t0 = _ecp_t0, t1 = _ecp_t1;
			fp_mul(s, fp_inv(t0, k, n, l), fp_add(t1, z, fp_mul(t1, r0, d, n, l), n, l), n, l);
			if (!mpn_zero_p(s, l)) {
				mpn_copyi(r, r0, l);
				break;
			}
		}
	}
}
446218
function _rsassa_pkcs1_v1_5_sign($m)
    {
        // EMSA-PKCS1-v1_5 encoding

        $em = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
        if ($em === false) {
            user_error('RSA modulus too short');
            return false;
        }

        // RSA signature

        $m = $this->_os2ip($em);
        $s = $this->_rsasp1($m);
        $s = $this->_i2osp($s, $this->k);

        // Output the signature S

        return $s;
    }
401797
def private_encrypt(key, message):
    '''
    
    '''
    if HAS_M2:
        return key.private_encrypt(message, salt.utils.rsax931.RSA_X931_PADDING)
    else:
        signer = salt.utils.rsax931.RSAX931Signer(key.exportKey('PEM'))
        return signer.sign(message)
676755
public static String signParams(SymmetricCrypto crypto, Map<?, ?> params, String separator, String keyValueSeparator, boolean isIgnoreNull) {
		if (MapUtil.isEmpty(params)) {
			return null;
		}
		String paramsStr = MapUtil.join(MapUtil.sort(params), separator, keyValueSeparator, isIgnoreNull);
		return crypto.encryptHex(paramsStr);
	}
1163612
function ECDSA({ x, y, d }) {
  if (x.length !== curveLength) throw new TypeError('Public EC Key point X of wrong length')
  if (y.length !== curveLength) throw new TypeError('Public EC Key point Y of wrong length')

  this.x = x
  this.y = y
  this.publicCodePoint = Buffer.concat([Buffer.from([0x04]), x, y])
  if (d) {
    this.d = d
    this.isPrivate = true
  } else {
    this.isPrivate = false
  }
}
484189
def sign(self, message, privkey, secret):
        
        m = self.GFn.value(message)
        x = self.GFn.value(privkey)
        k = self.GFn.value(secret)

        R = self.G * k

        r = self.GFn.value(R.x)
        s = (m + x * r) / k

        return (r, s)
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)
474295
def diffie_hellman(key2)

      lib = BTC::OpenSSL
      lib.autorelease do |pool|

        pk = pool.new_bn(key2.private_key)
        n = lib.group_order

        # Convert pubkey to a EC point
        pubkey_x = pool.new_bn(self.compressed_public_key)
        pubkey_point = pool.new_ec_point
        lib.EC_POINT_bn2point(lib.group, pubkey_x, pubkey_point, pool.bn_ctx)

        # Compute point = pubkey*pk + 0*G
        point = pool.new_ec_point
        # /** Computes r = generator * n + q * m
        #  *  \param  group  underlying EC_GROUP object
        #  *  \param  r      EC_POINT object for the result
        #  *  \param  n      BIGNUM with the multiplier for the group generator (optional)
        #  *  \param  q      EC_POINT object with the first factor of the second summand
        #  *  \param  m      BIGNUM with the second factor of the second summand
        #  *  \param  ctx    BN_CTX object (optional)
        #  *  \return 1 on success and 0 if an error occured
        #  */
        # int EC_POINT_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *n, const EC_POINT *q, const BIGNUM *m, BN_CTX *ctx);
        lib.EC_POINT_mul(lib.group, point, nil, pubkey_point, pk, pool.bn_ctx)

        # Check for invalid derivation.
        if 1 == lib.EC_POINT_is_at_infinity(lib.group, point)
          raise MathError, "Resulting point is at infinity."
        end

        lib.EC_POINT_point2bn(
          lib.group,
          point,
          self.public_key_compressed ?
          BTC::OpenSSL::POINT_CONVERSION_COMPRESSED :
          BTC::OpenSSL::POINT_CONVERSION_UNCOMPRESSED,
          pubkey_x,
          pool.bn_ctx
        )

        result_pubkey = lib.data_from_bn(pubkey_x, required_length: 33)
        return Key.new(public_key: result_pubkey)
      end
    end
963505
public static String rsaSign(String content, String privateKey) {

        if (null == content || privateKey == null) {
            return null;
        }

        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey, Base64.DEFAULT));
            KeyFactory keyf = KeyFactory.getInstance("RSA");
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);
            java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
            signature.initSign(priKey);
            signature.update(content.getBytes(CHARSET));
            byte[] signed = signature.sign();
            return Base64.encodeToString(signed, Base64.DEFAULT);
        } catch (Exception e) {
            //  这里是安全算法，为避免出现异常时泄露加密信息，这里不打印具体日志
            HMSAgentLog.e("rsaSign error");
        }

        return null;
    }
1090303
def sign(self, h):
        
        if not self.is_private():
            raise RuntimeError("Key must be private to be able to sign")
        val = from_bytes_32(h)
        r, s = self._generator.sign(self.secret_exponent(), val)
        return sigencode_der(r, s)
1002945
public static final KeyPair createKeyPair(BigInteger p, BigInteger g) throws GeneralSecurityException {
		KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
	    keyGen.initialize(new DHParameterSpec(p, g), new SecureRandom());
		return keyGen.generateKeyPair();
	}
469602
public static String sign(byte[] data, String privateKey) throws Exception {
        String keyBytes = Base64Utils.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes.getBytes());
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(privateK);
        signature.update(data);
        return String.valueOf(Base64Utils.encode(signature.sign()));
    }
776265
def sign(self, h, sig_format=SER_BINARY):
        
        outlen = (self.curve.sig_len_compact if sig_format == SER_COMPACT
                  else self.curve.sig_len_bin)
        sig = self._ECDSA_sign(h)
        return serialize_number(sig, sig_format, outlen)
866564
public byte[] sign(byte[] data) {
		lock.lock();
		try {
			signature.initSign(this.privateKey);
			signature.update(data);
			return signature.sign();
		} catch (Exception e) {
			throw new CryptoException(e);
		} finally {
			lock.unlock();
		}
	}
483135
function RSASetPrivateEx(N,E,D,P,Q,DP,DQ,C) {
  this.isPrivate = true;
  this.isPublic = false;
  if (N == null) throw "RSASetPrivateEx N == null";
  if (E == null) throw "RSASetPrivateEx E == null";
  if (N.length == 0) throw "RSASetPrivateEx N.length == 0";
  if (E.length == 0) throw "RSASetPrivateEx E.length == 0";

  if (N != null && E != null && N.length > 0 && E.length > 0) {
    this.n = parseBigInt(N,16);
    this.e = parseInt(E,16);
    this.d = parseBigInt(D,16);
    this.p = parseBigInt(P,16);
    this.q = parseBigInt(Q,16);
    this.dmp1 = parseBigInt(DP,16);
    this.dmq1 = parseBigInt(DQ,16);
    this.coeff = parseBigInt(C,16);
  } else {
    throw "Invalid RSA private key in RSASetPrivateEx";
  }
}
1211684
async function webSign(curve, hash_algo, message, keyPair) {
  const len = curve.payloadSize;
  const key = await webCrypto.importKey(
    "jwk",
    {
      "kty": "EC",
      "crv": webCurves[curve.name],
      "x": util.Uint8Array_to_b64(new Uint8Array(keyPair.getPublic().getX().toArray('be', len)), true),
      "y": util.Uint8Array_to_b64(new Uint8Array(keyPair.getPublic().getY().toArray('be', len)), true),
      "d": util.Uint8Array_to_b64(new Uint8Array(keyPair.getPrivate().toArray('be', len)), true),
      "use": "sig",
      "kid": "ECDSA Private Key"
    },
    {
      "name": "ECDSA",
      "namedCurve": webCurves[curve.name],
      "hash": { name: enums.read(enums.webHash, curve.hash) }
    },
    false,
    ["sign"]
  );

  const signature = new Uint8Array(await webCrypto.sign(
    {
      "name": 'ECDSA',
      "namedCurve": webCurves[curve.name],
      "hash": { name: enums.read(enums.webHash, hash_algo) }
    },
    key,
    message
  ));

  return {
    r: new BN(signature.slice(0, len)),
    s: new BN(signature.slice(len, len << 1))
  };
}
743262
byte[] DERToJOSE(byte[] derSignature) throws SignatureException {
        // DER Structure: http://crypto.stackexchange.com/a/1797
        boolean derEncoded = derSignature[0] == 0x30 && derSignature.length != ecNumberSize * 2;
        if (!derEncoded) {
            throw new SignatureException("Invalid DER signature format.");
        }

        final byte[] joseSignature = new byte[ecNumberSize * 2];

        //Skip 0x30
        int offset = 1;
        if (derSignature[1] == (byte) 0x81) {
            //Skip sign
            offset++;
        }

        //Convert to unsigned. Should match DER length - offset
        int encodedLength = derSignature[offset++] & 0xff;
        if (encodedLength != derSignature.length - offset) {
            throw new SignatureException("Invalid DER signature format.");
        }

        //Skip 0x02
        offset++;

        //Obtain R number length (Includes padding) and skip it
        int rLength = derSignature[offset++];
        if (rLength > ecNumberSize + 1) {
            throw new SignatureException("Invalid DER signature format.");
        }
        int rPadding = ecNumberSize - rLength;
        //Retrieve R number
        System.arraycopy(derSignature, offset + Math.max(-rPadding, 0), joseSignature, Math.max(rPadding, 0), rLength + Math.min(rPadding, 0));

        //Skip R number and 0x02
        offset += rLength + 1;

        //Obtain S number length. (Includes padding)
        int sLength = derSignature[offset++];
        if (sLength > ecNumberSize + 1) {
            throw new SignatureException("Invalid DER signature format.");
        }
        int sPadding = ecNumberSize - sLength;
        //Retrieve R number
        System.arraycopy(derSignature, offset + Math.max(-sPadding, 0), joseSignature, ecNumberSize + Math.max(sPadding, 0), sLength + Math.min(sPadding, 0));

        return joseSignature;
    }