简体   繁体   中英

Convert hmac function from python to Java

I want to convert the below python code to the same java code. I am not sure how to get the same result by using java. I tried to use hmacutils in apache codec package but the result is not the same. python code:

import hmac
import hashlib
secret_key = b"NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j"
total_params = b"/public/api/ver1/accounts/new?type=binance&name=binance_account&api_key=XXXXXX&secret=YYYYYY"
signature = hmac.new(secret_key, total_params, hashlib.sha384).hexdigest()
print("signature = {0}".format(signature))

With commons-codec:commons-codec:1.15

final byte[] key = "NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j".getBytes(StandardCharsets.UTF_8);
final Mac initializedMac = HmacUtils.getInitializedMac(HmacAlgorithms.HMAC_SHA_384, key);
final byte[] bytes = "/public/api/ver1/accounts/new?type=binance&name=binance_account&api_key=XXXXXX&secret=YYYYYY".getBytes(StandardCharsets.UTF_8);
initializedMac.update(bytes);
final byte[] digest = initializedMac.doFinal();
System.out.println(Hex.encodeHexString(digest));

Gives me output matching the output of that python snippet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM