Go and Python HMAC libraries give different results

Go and Python HMAC libraries give different results

By : ranhan429
Date : November 22 2020, 10:48 AM
around this issue I am trying to authenticate using HMAC/sha512 API key scheme. , Python dict is an unordered mapping type.
code :
>>> args = {}
>>> args['command'] = 'command'
>>> args['nonce'] = 10000
>>> list(args)
['nonce', 'command']  # <--- Iterating dictionary will yield in different order
                      #      with item insertion order
>>> import urllib
>>> urllib.urlencode({'command': 'command', 'nonce': 10000})
>>> urllib.urlencode([('command', 'command'), ('nonce', 10000)])
v.Set("command", method)
sign = hmac.new(secret, post_data, hashlib.sha512).hexdigest()
secret_bytes, _ := hex.DecodeString(privkey)
sighash := hmac.New(sha512.New, secret_bytes)
sighash := hmac.New(sha512.New, []byte(privkey))
func CallPrivate(method string, args map[string]string) {
    if args == nil {
        args = make(map[string]string)
    v := make(url.Values)
    v.Set("nonce", "3000000000") //strconv.Itoa(int((time.Now().Unix()))*1000))
    v.Set("command", method)
    for k, val := range args {
        v.Set(k, val)
    final_url := private_api_url
    post_data := v.Encode()
    sighash := hmac.New(sha512.New, []byte(privkey))
    sigstr := hex.EncodeToString(sighash.Sum(nil))

    client := &http.Client{}
    buf := bytes.NewBuffer([]byte(post_data))
    req, _ := http.NewRequest("POST", final_url, buf)
    req.Header.Set("Key", pubkey)
    req.Header.Set("Sign", sigstr)
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    res, _ := client.Do(req)
    defer res.Body.Close()

    res_body, _ := ioutil.ReadAll(res.Body)
    log.Printf("%s", string(res_body))

Share : facebook icon twitter icon
Why do I get wrong results for hmac in Python but not Perl?

Why do I get wrong results for hmac in Python but not Perl?

By : Qubical
Date : March 29 2020, 07:55 AM
wish of those help yes indeed -- it seems the Leopard version of python2.5 is the one that is broken.
below run on a Penryn-based MBP...
code :
$ **uname -a**
Darwin lizard-wifi 9.6.0 Darwin Kernel Version 9.6.0: Mon Nov 24 17:37:00 PST 2008; root:xnu-1228.9.59~1/RELEASE_I386 i386
dpc@lizard-wifi:~$ **which python**
dpc@lizard-wifi:~$ python
Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import hashlib, hmac
>>> print hmac.new("\x0b"*20, "Hi There", hashlib.sha512).hexdigest()
$ /opt/local/bin/python2.5
Python 2.5.4 (r254:67916, Feb  3 2009, 21:40:31) 
[GCC 4.0.1 (Apple Inc. build 5488)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import hashlib, hmac
>>> print hmac.new("\x0b"*20, "Hi There", hashlib.sha512).hexdigest()
Python HMAC-SHA1 vs Java HMAC-SHA1 different results

Python HMAC-SHA1 vs Java HMAC-SHA1 different results

By : miracle
Date : March 29 2020, 07:55 AM
this one helps. I think the problem is that in Java, you're using the raw bytes as the key (only converting them to a hex string for output):
code :
System.out.println("Key is..." + bytesToHex(keyBytes) + "\n");
// ...
SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW");
k = "3132333435363738393031323334353637383930"
raw_key = k.decode('hex')
Python encrypting using hmac and sha256 isn't giving the same results as javascript

Python encrypting using hmac and sha256 isn't giving the same results as javascript

By : ramss.net
Date : March 29 2020, 07:55 AM
To fix this issue msg_data from the python and json from the javascript are likely slightly different.
msg_data from the python:
code :
{"timestamp": "2017-12-11 23:31:55"}
{"timestamp":"2017-12-11 23:31:55"}
msg_data = json.dumps(data1, separators=(',', ':'))
How to implement HMAC in python without using the hmac library?

How to implement HMAC in python without using the hmac library?

By : Harshad Mohod
Date : March 29 2020, 07:55 AM
With these it helps I'm not understanding all the steps in your code, but here's a short example showing HMAC-SHA1 using only hashlib.sha1, with a helper function xor.
code :
import hashlib

def xor(x, y):
    return bytes(x[i] ^ y[i] for i in range(min(len(x), len(y))))

def hmac_sha1(key_K, data):
    if len(key_K) > 64:
        raise ValueError('The key must be <= 64 bytes in length')
    padded_K = key_K + b'\x00' * (64 - len(key_K))
    ipad = b'\x36' * 64
    opad = b'\x5c' * 64
    h_inner = hashlib.sha1(xor(padded_K, ipad))
    h_outer = hashlib.sha1(xor(padded_K, opad))
    return h_outer.digest()

def do_tests():
    # test 1
    k = b'\x0b' * 20
    data = b"Hi There"
    result = hmac_sha1(k, data)
    # add tests as desired
openssl hmac differ from python hmac

openssl hmac differ from python hmac

By : jkoreckyy
Date : March 29 2020, 07:55 AM
will help you It should be caused by the DATA string definition in your python code.
You need add r to treat the DATA as a raw string, such as
Related Posts Related Posts :
  • Appending a column in .csv with Python/Pandas
  • How to change my result directory in Robot framework using RIDE?
  • problem with using pandas to manipulate a big text file in python
  • python-magic module' object has no attribute 'open'
  • Where goes wrong for this High Pass Filter in Python?
  • Why inserting keys in order into a python dict is faster than doint it unordered
  • flann index saving in python
  • Create new instance of list or dictionary without class
  • How can I easily convert FORTRAN code to Python code (real code, not wrappers)
  • Address of lambda function in python
  • Python adding space between characters in string. Most efficient way
  • python http server, multiple simultaneous requests
  • Disguising username & password on distributed python scripts
  • Post GraphQL mutation with Python Requests
  • Why doesnt pandas create an excel file?
  • Rolling comparison between a value and a past window, with percentile/quantile
  • How to avoid repetitive code when defining a new type in python with signature verification
  • How to configure uWSGI in order to debug with pdb (--honour-stdin configuration issue)
  • In Python, how do you execute objects that are functions from a list?
  • Python- Variable Won't Subtract?
  • Processing Power In Python
  • Python 2.7.2 - Cannot import name _random or random from sys
  • Why doesn't the Python sorted function take keyword order instead of reverse?
  • Make a function redirect to other functions depending on a variable
  • get_absolute_url in django-categories
  • Monitoring non-Celery background task with New Relic in Python
  • Feature selection with LinearSVC
  • LSTM - Predicting the same constant values after a while
  • Test the length of elements in a list
  • Django: render radiobutton with 3 columns, cost column must change according to size & quantity selected
  • Python class attributes vs global variable
  • sys.stdout.writelines("hello") and sys.stdout.write("hello")
  • is ndarray faster than recarray access?
  • Python - search through directory trees, rename certain files
  • GAE: How to build a query where a string begins with a value
  • TypeError: __init__() takes at least 2 arguments (1 given)
  • Overriding and customizing "django.contrib.auth.views.login"
  • Django : Redirect to a particular page after login
  • Python search and copy files in directory
  • pretty printing numpy ndarrays using unicode characters
  • Frequent pattern mining in Python
  • How can I make a set of functions that can be used synchronously as well as asynchronously?
  • Convert one dice roll to two dice roll
  • count occourrence in a list
  • Writing an If condition to filter out the first word
  • to read file and compare column in python
  • Install python-numpy in the Virtualenv environment
  • `.select_by_visible_text()` is failed to select element?
  • Unable to send data multiple requests in a single connection — socket error
  • Pandas HDFStore unload dataframe from memory
  • Creating a custom admin view
  • How do you get the user role of the currently logged in user in Ckan?
  • Speed up Numpy Meshgrid Command
  • Python error - name lengths
  • appending text to a global variable
  • Python Mistake - Number of letters in name
  • Searching for a sequence in a text
  • Testing logging output with pytest
  • How do I change my default working directory for Python (Anaconda) on VSCode?
  • .lower() for x in list, not working, but works in another scenario
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org