加密方式
请求参数 依次从a-z排列 然后拼接后加入加密app_secret 然后MD5加密 即可得到签名字符串
PHP示例
private static function generateSign($params, $appSecret)
{
ksort($params);
$str = '';
foreach ($params as $key => $value) {
$str .= self::percentEncode($key). self::percentEncode($value);
}
$str .= $appSecret;
return md5($str);
}
private static function percentEncode($str)
{
// 使用urlencode编码后,将"+","*","%7E"做替换即满足 API规定的编码规范
$res = urlencode($str);
$res = preg_replace('/\+/', '%20', $res);
$res = preg_replace('/\*/', '%2A', $res);
$res = preg_replace('/%7E/', '~', $res);
return $res;
}
JAVA
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
public class SignGenerator {
private static String generateSign(Map<String, String> params, String appSecret) {
Map<String, String> sortedParams = new LinkedHashMap<>(params);
Collections.sort(sortedParams.keySet());
StringBuilder strBuilder = new StringBuilder();
for (Map.Entry<String, String> entry : sortedParams.entrySet()) {
strBuilder.append(percentEncode(entry.getKey()))
.append(percentEncode(entry.getValue()));
}
strBuilder.append(appSecret);
return md5(strBuilder.toString());
}
private static String percentEncode(String str) {
String encoded = java.net.URLEncoder.encode(str, "UTF-8");
encoded = encoded.replace("+", "%20");
encoded = encoded.replace("*", "%2A");
encoded = encoded.replace("%7E", "~");
return encoded;
}
}
Python
from urllib.parse import quote
import hashlib
def generate_sign(params, app_secret):
sorted_params = dict(sorted(params.items()))
str_to_hash = ''
for key, value in sorted_params.items():
str_to_hash += percent_encode(key) + percent_encode(value)
str_to_hash += app_secret
return hashlib.md5(str_to_hash.encode()).hexdigest()
def percent_encode(s):
res = quote(s)
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
Go
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
"sort"
"strings"
"net/url"
"regexp"
)
func generateSign(params map[string]string, appSecret string) string {
keys := make([]string, 0, len(params))
for k := range params {
keys = append(keys, k)
}
sort.Strings(keys)
var strToSign strings.Builder
for _, k := range keys {
strToSign.WriteString(percentEncode(k))
strToSign.WriteString(percentEncode(params[k]))
}
strToSign.WriteString(appSecret)
hasher := md5.New()
hasher.Write([]byte(strToSign.String()))
return hex.EncodeToString(hasher.Sum(nil))
}
func percentEncode(s string) string {
encoded := url.QueryEscape(s)
encoded = regexp.MustCompile(`\+`).ReplaceAllString(encoded, "%20")
encoded = regexp.MustCompile(`/\*/`).ReplaceAllString(encoded, "%2A")
encoded = strings.ReplaceAll(encoded, "%7E", "~")
return encoded
}
func main() {
params := map[string]string{"param1": "value1", "param2": "value2"}
appSecret := "yourAppSecret"
sign := generateSign(params, appSecret)
fmt.Println("Generated Sign:", sign)
}
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
public static class SignGenerator
{
public static string GenerateSign(Dictionary<string, string> paramsDict, string appSecret)
{
var sortedParams = new Dictionary<string, string>(paramsDict);
sortedParams = sortedParams.OrderBy(p => p.Key).ToDictionary(p => p.Key, p => p.Value);
var strBuilder = new StringBuilder();
foreach (var pair in sortedParams)
{
strBuilder.Append(PercentEncode(pair.Key)).Append(PercentEncode(pair.Value));
}
strBuilder.Append(appSecret);
return MD5Hash(strBuilder.ToString());
}
private static string PercentEncode(string str)
{
var encoded = Uri.EscapeDataString(str);
encoded = Regex.Replace(encoded, "\\+", "%20");
encoded = Regex.Replace(encoded, "\\*", "%2A");
encoded = Regex.Replace(encoded, "%7E", "~");
return encoded;
}
// 注意:这里需要一个MD5哈希方法,以下是一个简单的MD5实现示例
private static string MD5Hash(string input)
{
using (var md5 = System.Security.Cryptography.MD5.Create())
{
var hashBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
var hashStringBuilder = new StringBuilder();
foreach (var byteValue in hashBytes)
{
hashStringBuilder.Append(byteValue.ToString("x2"));
}
return hashStringBuilder.ToString();
}
}
}
ASP
<%
Option Explicit
Function GenerateSign(params, appSecret)
Dim sortedParams, str, key, value
Set sortedParams = CreateObject("Scripting.Dictionary")
For Each key In params.Keys
sortedParams.Add key, params(key)
Next
sortedParams.Sort
str = ""
For Each key In sortedParams.Keys
str = str & PercentEncode(sortedParams(key)) & PercentEncode(key)
Next
str = str & appSecret
GenerateSign = Hex(MD5(str))
End Function
Function PercentEncode(str)
Dim res
res = Server.URLEncode(str)
res = Replace(res, "+", "%20")
res = Replace(res, "*", "%2A")
res = Replace(res, "%7E", "~")
PercentEncode = res
End Function
' 假设已经有了一个MD5函数,这里只是一个占位符
Function MD5(input)
' 在ASP中,可能需要使用第三方库或自定义函数来计算MD5
' 这里只是简单地将输入的字符串转换为16进制表示
MD5 = Hex(CLng(input))
End Function
%>
标签:appKey,return,string,res,appSecret,params,str,验签,encoded
From: https://blog.csdn.net/Soujer/article/details/139240384