仅对字符串签名(SHA1 / sha1withRSA)

应用中应该使用的是 generateSign 方法

<code>
$string_wait_to_sign = urldecode(http_build_query($sorted_array));
$sign = self::signature($string_wait_to_sign);
</code>

@param string $encoded_query_string 待签名的字符串

@return string
496784
protected function signature(string $decoded_query_string)
    {
        // 优先使用私钥路径，否则取私钥值
        if ($this->alipay_app_private_key_path) {
            $private_key = file_get_contents( $this->alipay_app_private_key_path );
        } else {
            $private_key =
                "-----BEGIN RSA PRIVATE KEY-----\n" .
                $this->alipay_app_private_key .
                "\n-----END RSA PRIVATE KEY-----";
        }

        $resource = openssl_get_privatekey($private_key);

        openssl_sign($decoded_query_string, $signature, $resource);

        $signature = base64_encode($signature);

        return $signature;
    }
1234513
def sign(self, method, params):
        
        query_str = utils.percent_encode(params.items(), True)

        str_to_sign = "{0}&%2F&{1}".format(
            method, utils.percent_quote(query_str)
        )

        sig = hmac.new(
            utils.to_bytes(self._secret_key + "&"),
            utils.to_bytes(str_to_sign),
            hashlib.sha1
        )
        return base64.b64encode(sig.digest())
667312
public function MakeSign()
    {
        //签名步骤一：按字典序排序参数
        ksort($this->values);
        $string = $this->ToUrlParams();
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=" . $this->key;
        if ($this->IsSign_typeSet() && $this->GetSign_type() == 'HMAC-SHA256') {
            //签名步骤三：HMAC-SHA256加密
            $string = hash_hmac('sha256', $string, $this->key);
        } else {
            //签名步骤三：MD5加密
            $string = md5($string);
        }
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }
281588
def generate_message_signature(self, query_string):
        
        # split for sorting
        pairs = query_string.split('&')
        pairs = [pair.split('=', 1) for pair in pairs]
        pairs_sorted = sorted(pairs)
        pairs_string = '&' . join(['=' . join(pair) for pair in pairs_sorted])

        digest = hmac.new(self.key, b(pairs_string), hashlib.sha1).digest()
        signature = base64.b64encode(digest).decode('utf-8')

        return signature
531431
def request_signature(self, stringtosign):
        
        digest = hmac.new(
            self.secret_key.encode(ENCODING),
            stringtosign.encode(ENCODING),
            hashlib.sha1
        ).digest()
        return b64_string(digest)
219326
function getSignature ({
  params,
  accessKeySecret
}) {
  const paramString = paramsToString(params)
  const stringToSign = `POST&${encodeURIComponent('/')}&${encodeURIComponent(paramString)}`

  return crypto
    .createHmac('sha1', `${accessKeySecret}&`)
    .update(stringToSign)
    .digest('base64')
}
334311
public function MakeSign()
	{
		//签名步骤一：按字典序排序参数
		ksort($this->values);
		$string = $this->ToUrlParams();
		//签名步骤二：在string后加入KEY
		$string = $string . "&key=".WxPayConfig::$KEY;
		//签名步骤三：MD5加密
		$string = md5($string);
		//签名步骤四：所有字符转为大写
		$result = strtoupper($string);
		return $result;
	}
1229907
public function getSignature($params = [], $method = Alidayu::SIGN_METHOD_HMAC)
    {
        $rawQuery = [];
        ksort($params);
        foreach ($params as $k => $v) {
            $rawQuery[] = sprintf('%s%s', $k, $v);
        }
        $rawText = implode('', $rawQuery);
        $signature = '';
        if ($method === Alidayu::SIGN_METHOD_MD5) {
            $signature = md5($this->appSecret . $rawText . $this->appSecret);
        } elseif ($method === Alidayu::SIGN_METHOD_HMAC) {
            $signature = hash_hmac('md5', $rawText, $this->appSecret);
        }
        return strtoupper($signature);
    }
807166
public function generateWebhookSignature(
        string $url,
        \stdClass $data,
        string $secret_key
    ) {
        $signature = $url;
        $signature .= json_encode($data);

        return base64_encode(hash_hmac('sha1', $signature, $secret_key, true));
    }
1127593
protected function _sign_aliyun($params = array(),$method=self::METHOD){
    if (isset($params['sign_mode']) && $params['sign_mode'] == 1) {
      unset($params['items']);
    }
    $params = $this->_params_filter($params);
    $query = '';
    $arg = '';
    if(is_array($params) && !empty($params)){
        foreach($params as $key => $val) {
            $arg .= $this->_percentEncode($key) . "=" . $this->_percentEncode($val) . "&";
        }
      $query = substr($arg, 0, strlen($arg) - 2);
    }
    $base_string = strtoupper($method).'&%2F&' .$this->_percentEncode($query);
    return base64_encode(hash_hmac('sha1', $base_string, $this->secret."&", true));
  }
880988
function signSPKAC($signatureAlgorithm = 'sha1WithRSAEncryption')
    {
        if (!is_object($this->privateKey)) {
            return false;
        }

        $origPublicKey = $this->publicKey;
        $class = get_class($this->privateKey);
        $this->publicKey = new $class();
        $this->publicKey->loadKey($this->privateKey->getPublicKey());
        $this->publicKey->setPublicKey();
        $publicKey = $this->_formatSubjectPublicKey();
        if (!$publicKey) {
            return false;
        }
        $this->publicKey = $origPublicKey;

        $currentCert = isset($this->currentCert) ? $this->currentCert : null;
        $signatureSubject = isset($this->signatureSubject) ? $this->signatureSubject: null;

        // re-signing a SPKAC seems silly but since everything else supports re-signing why not?
        if (isset($this->currentCert) && is_array($this->currentCert) && isset($this->currentCert['publicKeyAndChallenge'])) {
            $this->currentCert['signatureAlgorithm']['algorithm'] = $signatureAlgorithm;
            $this->currentCert['publicKeyAndChallenge']['spki'] = $publicKey;
            if (!empty($this->challenge)) {
                // the bitwise AND ensures that the output is a valid IA5String
                $this->currentCert['publicKeyAndChallenge']['challenge'] = $this->challenge & str_repeat("\x7F", strlen($this->challenge));
            }
        } else {
            $this->currentCert = array(
                'publicKeyAndChallenge' =>
                    array(
                        'spki' => $publicKey,
                        // quoting <https://developer.mozilla.org/en-US/docs/Web/HTML/Element/keygen>,
                        // "A challenge string that is submitted along with the public key. Defaults to an empty string if not specified."
                        // both Firefox and OpenSSL ("openssl spkac -key private.key") behave this way
                        // we could alternatively do this instead if we ignored the specs:
                        // Random::string(8) & str_repeat("\x7F", 8)
                        'challenge' => !empty($this->challenge) ? $this->challenge : ''
                    ),
                    'signatureAlgorithm' => array('algorithm' => $signatureAlgorithm),
                    'signature'          => false // this is going to be overwritten later
            );
        }

        // resync $this->signatureSubject
        // save $publicKeyAndChallenge in case there are any \phpseclib\File\ASN1\Element objects in it
        $publicKeyAndChallenge = $this->currentCert['publicKeyAndChallenge'];
        $this->loadSPKAC($this->saveSPKAC($this->currentCert));

        $result = $this->_sign($this->privateKey, $signatureAlgorithm);
        $result['publicKeyAndChallenge'] = $publicKeyAndChallenge;

        $this->currentCert = $currentCert;
        $this->signatureSubject = $signatureSubject;

        return $result;
    }
42244
@SuppressWarnings("rawtypes")
    public static String createSign(String key, Map<String, Object> params) {
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
        Set es = params.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            parameters.put(k, v);
        }
        StringBuffer sb = new StringBuffer();
        Set es2 = parameters.entrySet();//accsii升序排序
        Iterator it2 = es2.iterator();
        while (it2.hasNext()) {
            Map.Entry entry = (Map.Entry) it2.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v)
                    && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + key);
        String sign = Lang.md5(sb.toString()).toUpperCase();
        return sign;
    }
980711
function getSignature(array $params, $method = null)
    {
        ksort($params);
        unset($params['sign']);
        unset($params['signature']);
        array_push($params, $this->secretKey);

        if ($method) {
            array_unshift($params, $method);
        }

        return hash('sha256', join('{up}', $params));
    }
622908
public static Map<String, String> sign(Map<String, String> reqData,String encoding) {
		reqData = SDKUtil.filterBlank(reqData);
		SDKUtil.sign(reqData, encoding);
		return reqData;
	}
651883
public function createSign($result, $key)
    {
        unset($result['sign']);

        ksort($result);

        $str = Helper::setParams($result);
        $str .= "&key=".$key;
        $sign = strtoupper(md5($str));

        return $sign;
    }
956576
public function sign($content) {
        if (is_array($content)) {
            $content = $this->getSignContent($content);
        }
        if ($this->signType == self::MD5
            || empty($this->privateKeyFile)) {
            return md5($content.$this->key);
        }
        if ($this->signType != self::RSA
            && $this->signType != self::RSA2) {
            return null;
        }
        $res = $this->getPrivateKeyResource();
        if (empty($res)) {
            throw new Exception('RSA私钥错误');
        }
        openssl_sign($content, $sign, $res,
            $this->signType == self::RSA ? OPENSSL_ALGO_SHA1 : OPENSSL_ALGO_SHA256);
        if (is_resource($res)) {
            openssl_free_key($res);
        }
        //base64编码
        return base64_encode($sign);
    }
151017
def generate_query_string(self, otp, nonce, timestamp=False, sl=None,
                              timeout=None):
        
        data = [('id', self.client_id),
                ('otp', otp),
                ('nonce', nonce)]

        if timestamp:
            data.append(('timestamp', '1'))

        if sl is not None:
            if sl not in range(0, 101) and sl not in ['fast', 'secure']:
                raise Exception('sl parameter value must be between 0 and '
                                '100 or string "fast" or "secure"')

            data.append(('sl', sl))

        if timeout:
            data.append(('timeout', timeout))

        query_string = urlencode(data)

        if self.key:
            hmac_signature = self.generate_message_signature(query_string)
            hmac_signature = hmac_signature
            query_string += '&h=%s' % (hmac_signature.replace('+', '%2B'))

        return query_string