java相当于python进行哈希处理

2024-09-22 16:25:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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来:

^{pr2}$

但在头中使用这个签名值执行post请求时,我得到

ValueError: Invalid header value 'XXXXXXXXXX'

我的python等价物正确吗?如果有人能解释的话,那将是很大的帮助!在

编辑

爪哇

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]:

Tags: keyinnewdatasecretstringmaccrypto
3条回答

如果你想简单点,试试这个:https://pythonhosted.org/pycrypto/Crypto.Hash.HMAC-module.html

可能编码会影响结果,[UTF-8]然后是[base-64]

pycrypto有一个散列函数https://pypi.python.org/pypi/pycrypto

由于值错误:无效的头值“xxxxxxxxx”请参阅此线程ValueError: Invalid header value 'H2O Python client/2.7.9 (default, Apr 2 2015, 15:33:21) \n[GCC 4.9.2]'

也许你文章的标题和你用来写文章的库不兼容

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

引用此线程:

{a1}

对于sha1,下面是简单等效的:

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

相关问题 更多 >