WebForm之企业微信开发(2)——准备Sha1签名算法,随机字符串及时间戳

发布时间 2023-03-28 13:40:40作者: 嬉戏_人间

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

/// <summary>
/// Sha1Helper 的摘要说明
/// </summary>
public class SHA1Helper
{
/// <summary>
/// 生成hmacsha1的散列
/// </summary>
/// <param name="word"></param>
/// <returns></returns>
public static string HmacSha1(string word)
{
return BitConverter.ToString(SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(word))).Replace("-", string.Empty);
}

 

/// 创建随机字符串
///本代码来自开源微信SDK项目:https://github.com/night-king/weixinSDK

private static string[] strs = new string[]

{
"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
};
public static string CreatenNonce_str()

{

Random r = new Random();

var sb = new StringBuilder();

var length = strs.Length;

for (int i = 0; i < 15; i++)

{

sb.Append(strs[r.Next(length - 1)]);

}

return sb.ToString();

}
/// 创建时间戳
///本代码来自开源微信SDK项目:https://github.com/night-king/weixinSDK

public static long CreatenTimestamp()

{
return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
}

 

///
/// <summary>
/// GetSignature
/// </summary>
/// <param name="jsapi_ticket"></param>
/// <param name="noncestr"></param>
/// <param name="timestamp"></param>
/// <param name="url"></param>
/// <param name="string1"></param>
/// <returns></returns>
public static string GetSignature(string jsapi_ticket, string noncestr, long timestamp, string url)

{

var string1Builder = new StringBuilder();

string1Builder.Append("jsapi_ticket=").Append(jsapi_ticket).Append("&")

.Append("noncestr=").Append(noncestr).Append("&")

.Append("timestamp=").Append(timestamp).Append("&")

.Append("url=").Append(url.IndexOf("#") >= 0 ? url.Substring(0, url.IndexOf("#")) : url);

string a = SHA1Helper.HmacSha1(string1Builder.ToString());

return a;

}
}