钉钉自定义机器人加签认证(HmacSHA256)C#实现

2021-03-17 02:26

阅读:695

标签:设置   int   cells   html   timezone   enc   x11   调用   table   

原文:钉钉自定义机器人加签认证(HmacSHA256)C#实现

0.UTF-8字符集

1.把timestamp+"\n"+密钥当做签名字符串,

2.使用HmacSHA256算法计算签名

3.然后进行Base64 encode

4.最后再把签名参数再进行urlEncode,得到最终的签名。

 

参数

说明

timestamp

当前时间戳,单位是毫秒,与请求调用时间误差不能超过1小时

secret

密钥,机器人安全设置页面,加签一栏下面显示的SEC开头的字符串

 

签名计算代码示例(Java)

?
1
2
3
4
5
6
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#版示例
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
        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}&timestamp={timeStamp}&sign={sign}";

  ok!


钉钉自定义机器人加签认证(HmacSHA256)C#实现

标签:设置   int   cells   html   timezone   enc   x11   调用   table   

原文地址:https://www.cnblogs.com/lonelyxmas/p/12409092.html


评论


亲,登录后才可以留言!