Reputation: 6683
I am sending requests to Kraken api using a private key. The problem is, generated signature is not as expected.
Please note that the key you can see below it's just a sample. But it should generate the expected output. If so, that means the code is correct and it would work with an actual key.
The goal is to perform the following encryption:
HMAC-SHA512 of (URI path + SHA256(nonce + POST data)) and base64 decoded secret API key
So far, I've written this code:
public class KrakenApi
{
private static string ApiPrivateKey = "kQH5HW/8p1uGOVjbgWA7FunAmGO8lsSUXNsu3eow76sz84Q18fWxnyRzBHCd3pd5nE9qa99HAZtuZuj6F1huXg==";
public static string GetKrakenSignature(string urlPath, ulong nonce, Dictionary<string,string> data)
{
var hash256 = new SHA256Managed();
var postData = string.Join("&", data.Select(e => e.Key + "=" + e.Value).ToArray());
var encoded = Encoding.UTF8.GetBytes(nonce + postData);
var message = Encoding.UTF8.GetBytes(urlPath).Concat(hash256.ComputeHash(encoded).ToArray());
var secretDecoded = (System.Convert.FromBase64String(ApiPrivateKey));
var hmacsha512 = new HMACSHA512(secretDecoded);
var hash = hmacsha512.ComputeHash(secretDecoded.Concat(message).ToArray());
return System.Convert.ToBase64String(hash);
}
}
Usage:
var data = new Dictionary<string, string> {
{ "nonce", "1616492376594" },
{ "ordertype", "limit" },
{ "pair", "XBTUSD" },
{ "price", "37500" },
{ "type", "buy" },
{ "volume", "1.25" }
};
var signature = KrakenApi.GetKrakenSignature("/0/private/AddOrder", ulong.Parse(data["nonce"]), data);
Console.WriteLine(signature);
Output should be:
4/dpxb3iT4tp/ZCVEwSnEsLxx0bqyhLpdfOpc6fn7OR8+UClSV5n9E6aSS8MPtnRfp32bAb0nmbRn6H8ndwLUQ==
There are a number of code samples for Phyton, Go, and Node JS that work correctly. But the above code in C# not generating expected output.
Upvotes: 1
Views: 577
Reputation: 6683
This generates the expected output. Finally I've read Python documentation for each method used in the code sample and reproduced the same steps in C#.
public static string GetKrakenSignature(string urlPath, ulong nonce, Dictionary<string,string> data)
{
var hash256 = new SHA256Managed();
var postData = string.Join("&", data.Select(e => e.Key + "=" + e.Value).ToArray());
var encoded = Encoding.UTF8.GetBytes(nonce + postData);
var message = Encoding.UTF8.GetBytes(urlPath).Concat(hash256.ComputeHash(encoded)).ToArray();
var mac = new HMACSHA512(Convert.FromBase64String(ApiPrivateKey));
return Convert.ToBase64String(mac.ComputeHash(message));
}
Upvotes: 2