java相当于python for hashing

时间:2016-02-17 18:39:33

标签: java python hash hmac hmacsha1

我在java文档中有以下代码(它需要secret_keydata作为输入):

javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1")
mac.init(new javax.crypto.spec.SecretKeySpec(secret_key.getBytes(), "HmacSHA1"))
byte[] hexBytes = new org.apache.commons.codec.binary.Hex().encode(mac.doFinal(data.getBytes()))
String signature = new String(hexBytes, "UTF-8")

在网上做了一些RnD之后,我写了等价的python:

decodedKey = secret_key.decode("hex")
hmac_val = hmac.new(decodedKey, data.encode('UTF-8'), hashlib.sha1)
signature = hmac_val.digest().encode('base64')

但是在标题中使用此签名值执行发布请求时,我正在

  

ValueError:标头值无效' XXXXXXXXXX'

我的python等价正确吗?如果有人可以解释,那将是很有帮助的!

修改

Java

public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
        String secret_key = "c84766ca4a3ce52c3602bbf02ad1f7";
        String data = "some data";
        javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1");
        mac.init(new javax.crypto.spec.SecretKeySpec(secret_key.getBytes(), "HmacSHA1"));
        byte[] hexBytes = new org.apache.commons.codec.binary.Hex().encode(mac.doFinal(data.getBytes()));
        String signature = new String(hexBytes, "UTF-8");
        System.out.println("signature : "+signature);
 }

O / P

signature : 2b565c0476eed0f350ddb3a2852a4cab91281bdc

Python:

In [1]: import hmac

In [2]: import hashlib

In [3]: secret_key = "c84766ca4a3ce52c3602bbf02ad1f7"

In [4]: data = "some data"

In [5]: decodedKey = secret_key.decode("hex")

In [6]: hmac_val = hmac.new(decodedKey, data.encode('UTF-8'), hashlib.sha1)

In [7]: signature = hmac_val.digest().encode('base64')

In [8]: signature
Out[8]: '3qE5SqSdvBEJcy8mSF+srqNXCd4=\n'

In [9]:

3 个答案:

答案 0 :(得分:1)

参考此主题:

Java method which can provide the same output as Python method for HMAC-SHA256 in Hex

sha1的轻微推文,下面简单等效:

In [13]: print hmac.new(secret_key, data, hashlib.sha1).hexdigest()
2b565c0476eed0f350ddb3a2852a4cab91281bdc

答案 1 :(得分:0)

pycrypto 有一个哈希函数https://pypi.python.org/pypi/pycrypto

ValueError:无效的标头值' XXXXXXXXXX' 看到此帖子ValueError: Invalid header value 'H2O Python client/2.7.9 (default, Apr 2 2015, 15:33:21) \n[GCC 4.9.2]'

您帖子中的标题可能与您用于帖子的库不兼容

你在python代码中导入了哪些库?

答案 2 :(得分:0)

如果您想轻松试试这个:https://pythonhosted.org/pycrypto/Crypto.Hash.HMAC-module.html

也许编码会影响结果,[UTF-8]然后[base-64]