亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用哈希進行身份驗證

使用哈希進行身份驗證

慕的地6264312 2022-09-13 10:10:27
我需要使用我不理解的復雜身份驗證過程與 API 建立連接。我知道它涉及多個步驟,我試圖模仿它,但我發現文檔非?;靵y......這個想法是,我向一個端點發出請求,該端點將向我返回一個令牌,我需要使用它來建立websocket連接。我確實得到了一個代碼示例,它是在Python中,我不知道它的語法,但我可以把它作為一個指南,把它轉換為C#語法。這是蟒蛇代碼示例:import time, base64, hashlib, hmac, urllib.request, jsonapi_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        }    }所以下一部分是我真正掙扎的地方。需要做一些HMAC計算,但我完全迷失在那里。
查看完整描述

1 回答

?
www說

TA貢獻1775條經驗 獲得超8個贊

這里的主要任務是反轉SHA-512 HMAC計算。使用日期時間偏移.Now.ToUnix時間毫秒獲取API,它將返回一個Unix時間戳毫秒值。然后,這一切都歸結為串聯字節數組并生成哈希值。我使用硬編碼時間只是為了演示結果;每次計算密鑰時,您必須取消注釋才能獲得當前的Unix時間戳毫秒。API-Signnonceapi_noncestring ApiNonce = DateTimeOffset.Now.ToUnixTimeMillisecondsAPI-Sign


蟒蛇生成: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 小提琴中的結果。


查看完整回答
反對 回復 2022-09-13
  • 1 回答
  • 0 關注
  • 164 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號