Petr Javorik
Petr Javorik

Reputation: 1863

Kraken API MATLAB client invalid signature error

I'm trying to do some authenticated calls to Kraken private endpoints but without success. I'm still getting an error EAPI:Invalid signature. Does anybody know what's wrong?

Here's the code:

function [response,status]=kraken_authenticated(uri,postdata)

  % test uri='0/private/AddOrder'
  % test postdata='&pair=XBTEUR&type=buy&ordertype=limit&price=345.214&volume=0.65412&leverage=1.5&oflags=post'

  url=['https://api.kraken.com/',uri];
  % nonce
  nonce = num2str(floor((now-datenum('1970', 'yyyy'))*8640000000));
  [key,secret]=key_secret('kraken');
  % 1st hash
  Opt.Method = 'SHA-256';
  Opt.Input  = 'ascii';
  sha256string = DataHash(['nonce=',nonce,postdata],Opt);
  % 2nd hash
  sign = crypto([uri,sha256string], secret, 'HmacSHA512');

  header_1=http_createHeader('API-Key',key);
  header_2=http_createHeader('API-Sign',char(sign));
  header=[header_1 header_2];
  [response,status] = urlread2(url,'POST',['nonce=',nonce,postdata],header);

end

Crypto function is in another file:

function signStr = crypto(str, key, algorithm)

  import java.net.*;
  import javax.crypto.*;
  import javax.crypto.spec.*;
  import org.apache.commons.codec.binary.*

  keyStr = java.lang.String(key);
  key = SecretKeySpec(keyStr.getBytes('UTF-8'), algorithm);
  mac = Mac.getInstance(algorithm);
  mac.init(key);
  toSignStr = java.lang.String(str);
  signStr = java.lang.String(Hex.encodeHex( mac.doFinal( toSignStr.getBytes('UTF-8'))));

end

I've also tried

sign = crypto([uri,sha256string], base64decode(secret), 'HmacSHA512');

but without success.

This is guide for authenticated call HTTPS Header:

API-Key = API key
API-Sign = Message signature using HMAC-SHA512 of (URI path + SHA256(nonce + POST data)) and base64 decoded secret API key

This is guide for authenticated call POST Data:

nonce = always increasing unsigned 64 bit integer
otp = two-factor password (if two-factor enabled, otherwise not required)

I've tried to pass "nonce" parameter or all parameters in "postdata" to POST data but without success.

Thanks for help.

Upvotes: 1

Views: 1262

Answers (1)

f334e31bd0
f334e31bd0

Reputation: 48

The problem is in function crypto here:

keyStr = java.lang.String(key);
key = SecretKeySpec(keyStr.getBytes('UTF-8'), algorithm);

As the base64 encoded private key from kraken is not necessarily UTF-8 encoded, you cannot use UTF-8 encoding to extract the key and pass UTF-8 string to the SecretKeySpec function. You need to use byte array instead.

Similar issues

https://code.google.com/p/google-apps-script-issues/issues/detail?id=5113 https://code.google.com/p/google-apps-script-issues/issues/detail?id=3121

Solution for javascript

github.com/Caligatio/jsSHA

Upvotes: 2

Related Questions