title: Apply HMAC SHA-512 algorithm using a secret key in python
body: <p>I am trying to Apply HMAC SHA-512 algorithm using a secret key in python but I am not finding the correct way to sign.</p>
  
  <p>I was able to do using nodejs and c# but not for python</p>
  
  <p>in nodejs</p>
  
  <pre><code>return crypto.createHmac('sha512', new Buffer(secretString, 'base64')).update(new Buffer(stringToSign)).digest('base64');
  </code></pre>
  
  <p>in c#</p>
  
  <pre><code>byte[] secretkeyBytes = Encoding.UTF8.GetBytes(apiSecret);
  byte[] inputBytes = Encoding.UTF8.GetBytes(stringToSign);
  using (var hmac = new HMACSHA512(secretkeyBytes))
  {
    byte[] hashValue = hmac.ComputeHash(inputBytes);
    signature = System.Convert.ToBase64String(hashValue);
  }
  </code></pre>
  
  <p>but in python I am not figuring a way to do that.
  I already tried:</p>
  
  <pre><code>b_secret_string=base64.b64encode(secret_string.encode('utf-8'))
  hash = hmac.new(base64.b64encode(b_secret_string),'',sha512)
  hash.update(string_to_sign.encode('utf-8'))
  signature = base64.b64encode(hash.digest())
  </code></pre>
  
  <p>and</p>
  
  <pre><code>hashed = hmac.new(str(secret_string.encode('utf-8')),'',sha512)
  hashed.update(string_to_sign.encode('utf-8'))
  signature = base64.b64encode(hashed.digest())
  </code></pre>
  
  <p>but it is not working. If possible can someone give me a light? I really appreciate it.</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>Also tried with the following:</p>
  
  <pre><code>string_to_sign = string_to_sign.encode('utf-8')
  secret_string = secret_string.encode('utf-8')
  hash = hmac.new(secret_string, string_to_sign, hashlib.sha512)
  signature = base64.b64encode(hash.digest())
  </code></pre>
  
  <p>tried using hexdigest() too:</p>
  
  <pre><code>signature = base64.b64encode(hash.hexdigest())
  </code></pre>
  
  <p>if someone wants to test it. Should return the same as this code in nodejs.</p>
  
  <pre><code>var crypto = require('crypto');
  
  a = new Buffer('PRIVATE_KEY', 'base64');
  hash = crypto.createHmac('sha512', a)
  stringToSign = 'Stack OverFlow Funtime';
  hash.update(new Buffer(stringToSign));
  console.log(hash.digest('base64'));
  
  $ node example.js
  ugmH0VdttdAxGdpzNJnaNn1KlVS4wBzoK//dsPuvK65Zsl8FgT+3aLGnsEubThlv5/3chfyMmsUH//LdS1MXqg==
  </code></pre>