http请求签名生成算法

算法文档: 签名生成算法

签名生成步骤
步骤1、请求参数拼接为有序字符串
步骤2、将签名字符串使用MD5摘要算法生成MD5值
步骤3、将生成的签名追加到原参数后

lua实现

local md5 = require("md5") -- 使用 Lua 的 md5 库,你可能需要安装相应的库

function generateSign(params)
    local signParams = {}

    -- 步骤1:参数按照键名进行字典序排序
    for k, v in pairs(params) do
        if k ~= "sign" and v ~= "" then
            table.insert(signParams, k .. "=" .. tostring(v))
        end
    end
    table.sort(signParams)

    -- 步骤2:使用MD5算法生成MD5值
    local signStr = table.concat(signParams, "&")
    local md5Sign = md5.sumhexa(signStr):upper()

    -- 步骤3:将生成的签名追加到原参数后
    params.sign = md5Sign
    return params
end

function verifySign(params)
    local sign = params.sign
    params.sign = nil

    -- 重新生成签名
    local generatedParams = generateSign(params)
    local generatedSign = generatedParams.sign

    -- 验证签名是否一致
    return sign == generatedSign
end

-- 举例
local params = {
    appId = "ai6ydn7d6okgv2038o",
    outTradeNo = "278347285372910411",
    openId = "soilq51g52bWOgmeKB6Lbjd60oMk",
    amount = 1,
    attach = "mark消息",
    notifyUrl = "https://openplatform-openapi.soulapp.cn/order/notifyUrl",
    nonceStr = "742945738482093302",
    signType = "MD5",
}

-- 生成签名
local signedParams = generateSign(params)
print("Generated Signature:", signedParams.sign)

-- 验证签名
local isValid = verifySign(signedParams)
print("Is Valid Signature:", isValid)

Golang版本

package main

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"net/url"
	"sort"
	"strings"
)

// generateSign 生成签名
func generateSign(params map[string]string) string {
	// 步骤1:参数按照键名进行字典序排序
	keys := make([]string, 0, len(params))
	for k := range params {
		if k != "sign" && params[k] != "" {
			keys = append(keys, k)
		}
	}
	sort.Strings(keys)

	// 步骤2:使用 MD5 算法生成 MD5 值
	var signStrings []string
	for _, key := range keys {
		signStrings = append(signStrings, key+"="+params[key])
	}
	signStr := strings.Join(signStrings, "&")
	hash := md5.New()
	hash.Write([]byte(signStr))
	md5Sign := hex.EncodeToString(hash.Sum(nil))

	// 步骤3:将生成的签名追加到原参数中
	params["sign"] = strings.ToUpper(md5Sign)
	return params["sign"]
}

// verifySign 验证签名
func verifySign(params map[string]string) bool {
	sign := params["sign"]
	delete(params, "sign")

	// 重新生成签名
	generatedSign := generateSign(params)

	// 验证签名是否一致
	return sign == generatedSign
}

func main() {
	// 举例
	params := map[string]string{
		"appId":      "ai6ydn7d6okgv2038o",
		"outTradeNo": "278347285372910411",
		"openId":     "soilq51g52bWOgmeKB6Lbjd60oMk",
		"amount":     "1",
		"attach":     "mark消息",
		"notifyUrl":  "https://openplatform-openapi.soulapp.cn/order/notifyUrl",
		"nonceStr":   "742945738482093302",
		"signType":   "MD5",
	}

	// 生成签名
	sign := generateSign(params)
	fmt.Println("Generated Signature:", sign)

	// 验证签名
	isValid := verifySign(params)
	fmt.Println("Is Valid Signature:", isValid)
}

你可能感兴趣的:(golang,http,算法,golang,lua)