钉钉自定义机器人加签认证(HmacSHA256)C#实现
2021-03-17 02:26
标签:设置 int cells html timezone enc x11 调用 table
0.UTF-8字符集 1.把timestamp+"\n"+密钥当做签名字符串, 2.使用HmacSHA256算法计算签名 3.然后进行Base64 encode 4.最后再把签名参数再进行urlEncode,得到最终的签名。 参数 说明 timestamp 当前时间戳,单位是毫秒,与请求调用时间误差不能超过1小时 secret 密钥,机器人安全设置页面,加签一栏下面显示的SEC开头的字符串 签名计算代码示例(Java) ok! 钉钉自定义机器人加签认证(HmacSHA256)C#实现 标签:设置 int cells html timezone enc x11 调用 table 原文地址:https://www.cnblogs.com/lonelyxmas/p/12409092.html
Long timestamp = System.currentTimeMillis();
String stringToSign = timestamp +
"\n"
+ secret;
Mac mac = Mac.getInstance(
"HmacSHA256"
);
mac.init(
new
SecretKeySpec(secret.getBytes(
"UTF-8"
),
"HmacSHA256"
));
byte
[] signData = mac.doFinal(stringToSign.getBytes(
"UTF-8"
));
return
URLEncoder.encode(
new
String(Base64.encodeBase64(signData)),
"UTF-8"
);
C#版示例
private
static
byte
[] getHmac(
string
message,
string
secret)
{
byte
[] keyByte = Encoding.UTF8.GetBytes(secret);
byte
[] messageBytes = Encoding.UTF8.GetBytes(message);
using
(
var
hmacsha256 =
new
HMACSHA256(keyByte))
{
byte
[] hashmessage = hmacsha256.ComputeHash(messageBytes);
return
hashmessage;
}
}
public
static
Int64 ToUTC(
this
DateTime time)
{
var
zts = TimeZoneInfo.Local.BaseUtcOffset;
var
yc =
new
DateTime(1970, 1, 1).Add(zts);
return
(
long
)(DateTime.Now - yc).TotalMilliseconds;
}
main.cs
var
secret =
"123"
;
var
timeStamp = DateTime.Now.ToUTC();
var
stringToSign = $
"{timeStamp}\n{secret}"
;
var
b64 = getHmac(stringToSign, secret);
var
b64Str = Convert.ToBase64String(b64);
var
sign = HttpUtility.UrlEncode(b64Str);
url = $
"{url}×tamp={timeStamp}&sign={sign}"
;
下一篇:钉钉二次开发c#发起审批
文章标题:钉钉自定义机器人加签认证(HmacSHA256)C#实现
文章链接:http://soscw.com/index.php/essay/65120.html