gpt4 book ai didi

c# - 使用散列进行身份验证

转载 作者:行者123 更新时间:2023-12-03 14:07:40 27 4
gpt4 key购买 nike

我需要使用我不理解的复杂身份验证过程连接到 API。
我知道它涉及多个步骤,我试图模仿它,但我发现文档非常困惑......

这个想法是我向端点发出请求,该端点将向我返回一个 token ,我需要使用该 token 来建立 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 计算,但我完全迷失在那里。

最佳答案

这里的主要任务是反转API-Sign SHA-512 HMAC 计算。使用 DateTimeOffset.Now.ToUnixTimeMilliseconds 获取 API nonce ,它将返回一个 Unix 时间戳毫秒值。然后这一切都归结为连接字节数组并生成哈希。我正在使用硬编码 api_nonce时间只是为了证明结果;你必须取消注释 string ApiNonce = DateTimeOffset.Now.ToUnixTimeMilliseconds每次 API-Sign 时获取当前的 Unix 时间戳毫秒键被计算。

python API-Sign一代:

import time, base64, hashlib, hmac, urllib.request, json

# Hardcoce API_PRIVATE_KEY base 64 value
API_PRIVATE_KEY = base64.encodebytes(b"some_api_key_1234")

# time_use = time.time()
# Hardcode the time so we can confirm the same result to C#
time_use = 1586096626.919

api_nonce = bytes(str(int(time_use*1000)), "utf-8")

print("API nonce: %s" % api_nonce)

api_request = urllib.request.Request("https://www.website.com/getToken", b"nonce=%s" % api_nonce)
api_request.add_header("API-Key", "API_PUBLIC_KEY_1234")

print("API_PRIVATE_KEY: %s" % API_PRIVATE_KEY)

h256Dig = hashlib.sha256(api_nonce + b"nonce=%s" % api_nonce).digest()

api_sign = base64.b64encode(hmac.new(base64.b64decode(API_PRIVATE_KEY), b"/getToken" + h256Dig, hashlib.sha512).digest())

# api_request.add_header("API-Sign", api_sign)
# print(json.loads(urllib.request.urlopen(api_request).read())['result']['token'])

print("API-Sign: %s" % api_sign)

将输出:
API nonce: b'1586096626919'
API_PRIVATE_KEY: b'c29tZV9hcGlfa2V5XzEyMzQ=\n'
API-Sign: b'wOsXlzd3jOP/+Xa3AJbfg/OM8wLvJgHATtXjycf5EA3tclU36hnKAMMIu0yifznGL7yhBCYEwIiEclzWvOgCgg=='

C# API-Sign一代:

static string apiPublicKey = "API_PUBLIC_KEY";
// Hardcoce API_PRIVATE_KEY base 64 value
static string apiPrivateKey = Base64EncodeString("some_api_key_1234");
static string endPoint = "https://www.website.com/getToken";

public static void Main()
{
Console.WriteLine("API-Sign: '{0}'", GenApiSign());
}

static private string GenApiSign()
{
// string ApiNonce = DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString();
// Hardcode the time so we can confirm the same result with Python
string ApiNonce = "1586096626919";

Console.WriteLine("API nonce: {0}", ApiNonce);
Console.WriteLine("API_PRIVATE_KEY: '{0}'", apiPrivateKey);

byte[] ApiNonceBytes = Encoding.Default.GetBytes(ApiNonce);

byte[] h256Dig = GenerateSHA256(CombineBytes(ApiNonceBytes, Encoding.Default.GetBytes("nonce="), ApiNonceBytes));
byte[] h256Token = CombineBytes(Encoding.Default.GetBytes("/getToken"), h256Dig);

string ApiSign = Base64Encode(GenerateSHA512(Base64Decode(apiPrivateKey), h256Token));

return ApiSign;
}

// Helper functions ___________________________________________________

public static byte[] CombineBytes(byte[] first, byte[] second)
{
byte[] ret = new byte[first.Length + second.Length];
Buffer.BlockCopy(first, 0, ret, 0, first.Length);
Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
return ret;
}

public static byte[] CombineBytes(byte[] first, byte[] second, byte[] third)
{
byte[] ret = new byte[first.Length + second.Length + third.Length];
Buffer.BlockCopy(first, 0, ret, 0, first.Length);
Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
Buffer.BlockCopy(third, 0, ret, first.Length + second.Length,
third.Length);
return ret;
}


public static byte[] GenerateSHA256(byte[] bytes)
{
SHA256 sha256 = SHA256Managed.Create();
return sha256.ComputeHash(bytes);
}

public static byte[] GenerateSHA512(byte[] key, byte[] bytes)
{
var hash = new HMACSHA512(key);
var result = hash.ComputeHash(bytes);

hash.Dispose();

return result;
}

public static string Base64EncodeString(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}

public static string Base64Encode(byte[] bytes)
{
return System.Convert.ToBase64String(bytes);
}

public static byte[] Base64Decode(string base64EncodedData)
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return base64EncodedBytes;
}

将输出:
API nonce: 1586096626919
API_PRIVATE_KEY: 'c29tZV9hcGlfa2V5XzEyMzQ='
API-Sign: 'wOsXlzd3jOP/+Xa3AJbfg/OM8wLvJgHATtXjycf5EA3tclU36hnKAMMIu0yifznGL7yhBCYEwIiEclzWvOgCgg=='

您可以在此 .NET Fiddle 中看到它的工作和结果.

关于c# - 使用散列进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60858424/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com