【发布时间】:2020-07-06 13:32:50
【问题描述】:
我需要使用我不理解的复杂身份验证过程连接到 API。 我知道它涉及多个步骤,并且我试图模仿它,但我发现文档非常混乱......
我的想法是我向端点发出请求,该端点将返回一个令牌给我,我需要使用它来建立 websocket 连接。
我确实得到了一个我不知道其语法的 Python 代码示例,但我可以将其用作将其转换为 C# 语法的指南。
这是 Python 代码示例:
import time, base64, hashlib, hmac, urllib.request, json
api_nonce = bytes(str(int(time.time()*1000)), "utf-8")
api_request = urllib.request.Request("https://www.website.com/getToken", b"nonce=%s" % api_nonce)
api_request.add_header("API-Key", "API_PUBLIC_KEY")
api_request.add_header("API-Sign", base64.b64encode(hmac.new(base64.b64decode("API_PRIVATE_KEY"), b"/getToken" + hashlib.sha256(api_nonce + b"nonce=%s" % api_nonce).digest(), hashlib.sha512).digest()))
print(json.loads(urllib.request.urlopen(api_request).read())['result']['token'])
所以我尝试将其转换为 C#,这是我目前得到的代码:
static string apiPublicKey = "API_PUBLIC_KEY";
static string apiPrivateKey = "API_PRIVATE_KEY";
static string endPoint = "https://www.website.com/getToken";
private void authenticate()
{
using (var client = new HttpClient())
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
// CREATE THE URI
string uri = "/getToken";
// CREATE THE NONCE
/// NONCE = unique identifier which must increase in value with each API call
/// in this case we will be using the epoch time
DateTime baseTime = new DateTime(1970, 1, 1, 0, 0, 0);
TimeSpan epoch = CurrentTime - baseTime;
Int64 nonce = Convert.ToInt64(epoch.TotalMilliseconds);
// CREATE THE DATA
string data = string.Format("nonce={0}", nonce);
// CALCULATE THE SHA256 OF THE NONCE
string sha256 = SHA256_Hash(data);
// DECODE THE PRIVATE KEY
byte[] apiSecret = Convert.FromBase64String(apiPrivateKey);
// HERE IS THE HMAC CALCULATION
}
}
public static String SHA256_Hash(string value)
{
StringBuilder Sb = new StringBuilder();
using (var hash = SHA256.Create())
{
Encoding enc = Encoding.UTF8;
Byte[] result = hash.ComputeHash(enc.GetBytes(value));
foreach (Byte b in result)
Sb.Append(b.ToString("x2"));
}
return Sb.ToString();
}
所以下一部分是我真正挣扎的地方。需要进行一些 HMAC 计算,但我完全迷路了。
【问题讨论】:
-
您能提供文档链接吗?
-
你不能用HMACSHA512类吗?
-
您需要在 python 中调试一个静态示例,以便您可以检查进度并查看它在 C# 实现中的偏差。使用将在 Python 示例和 C# 实现中使用的硬编码时间值。您应该只需要运行一次 Python 示例并在此过程中打印出关键变量,然后将其保存以与您的 C# 实现进行比较。