之前项目对接用的时apiKey的方式,现在看提示不安全,所以想着提前准备,但是平台提供的只有python和java的token生成方式,C#的代码链接点开提示不存在,我去,只能花时间自己写一个了。
调用:
string result = “”;
result = OneNetNewPlatForm.CreateAccessKey(“products/123123”, “1537255523”, “你的apiKey”, “md5/sha1/sha256”, “2018-10-31”);
题外话:
最后这个version 好多版本 我看提供的token生成器都支持,调用api也没报错。
/// <summary>
/// onenet物联网平台 安全鉴权 Token生成算法
/// </summary>
/// <param name="res">访问资源 resource 格式为:父资源类/父资源ID/子资源类/子资源ID </param>
/// <param name="et">访问过期时间 expirationTime,unix时间 当一次访问参数中的et时间小于当前时间时,平台会认为访问参数过期从而拒绝该访问</param>
/// <param name="key"> apiKey </param>
/// <param name="method">支持hmac md5,sha1,sha256 </param>
/// <param name="version"></param>
/// <returns></returns>
public static string CreateAccessKey(string res, string et, string key, string method, string version = "2018-10-31")
{
string accessKey = "";
try
{
string StringForSignature = et + '\n' + method + '\n' + res + '\n' + version;
string sign = "";
switch (method)
{
case "sha1":
using (HMACSHA1 hmac = new HMACSHA1(Convert.FromBase64String(key)))
{
byte[] hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(StringForSignature));
sign = Convert.ToBase64String(hashBytes).Replace("=", "%3D").Replace("+", "%2B").Replace("#", "%23").Replace("&", "%26").Replace("/", "%2F");
}
break;
case "sha256":
using (HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(key)))
{
byte[] hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(StringForSignature));
sign = Convert.ToBase64String(hashBytes).Replace("=", "%3D").Replace("+", "%2B").Replace("#", "%23").Replace("&", "%26").Replace("/", "%2F");
}
break;
case "md5":
using (HMACMD5 hmac = new HMACMD5(Convert.FromBase64String(key)))
{
byte[] hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(StringForSignature));
sign = Convert.ToBase64String(hashBytes).Replace("=", "%3D").Replace("+", "%2B").Replace("#", "%23").Replace("&", "%26").Replace("/", "%2F");
}
break;
}
sign = UnicodeEncoding.UTF8.GetString(UnicodeEncoding.UTF8.GetBytes(sign));
accessKey = string.Format("version={0}&res={1}&et={2}&method={3}&sign={4}", version, res, et, method, sign);
}
catch (Exception ex)
{
}
return accessKey;
}