简体   繁体   English

从 javascript 参考案例在 python 中重现 hmac 操作

[英]Reproducing an hmac operation in python from the javascript reference case

I have a fragment of javascript that operates properly:我有一个运行正常的 javascript 片段:

let seed = '319aa8124bbcddac2bae8438cfd5e658aeca56d524736739622dfb0a09942b22';
let salt = '0000000000000000004d6ec16dafe9d8370958664c1dc422f452892264c59526';
// 1. HMAC_SHA256(message=seed, key=salt)  
const hmac = CryptoJS.HmacSHA256(CryptoJS.enc.Hex.parse(seed), salt);
let foo = hmac.toString(CryptoJS.enc.Hex);
console.log("foo", hmac.toString(CryptoJS.enc.Hex));  //foo fe6a57f08b9970b7cd497e627afac956203a8ef829d2d97c7967775c1c0b6f6a

I try to reproduce it in python:我尝试在 python 中重现它:

seed = "319aa8124bbcddac2bae8438cfd5e658aeca56d524736739622dfb0a09942b22"
salt = "0000000000000000004d6ec16dafe9d8370958664c1dc422f452892264c59526"
hm = hmac.new(str.encode(seed), b'', hashlib.sha256)
hm.update(salt.encode("utf-8"))
h = hm.hexdigest()
print(h)   # returns 01703d8db07432ca416151099533b60baea7a6450fc5b88788c7ca9af921b4a1

but the result is incorrect.但结果不正确。

I think the step I'm missing is the CryptoJS.enc.Hex.parse(seed) operation that occurs in the javascript.我认为我缺少的步骤是在 javascript 中发生的CryptoJS.enc.Hex.parse(seed)操作。 I don't understand what that is doing to the seed value.我不明白这对种子价值有什么影响。 I try to console.log() that value but it returns a complicated object that I don't comprehend.我尝试使用console.log()该值,但它返回一个我不理解的复杂对象。

So my questions are:所以我的问题是:

  1. what is that function doing to the the seed该函数对seed什么作用
  2. how to do the equivalent in python.如何在python中做等价的。

These algorithms work on raw bytes.这些算法适用于原始字节。 Your seed is representing those bytes in hexadecimal, ie 31 is one byte, 9a is another.您的种子以十六进制表示这些字节,即31是一个字节, 9a是另一个字节。 CryptoJS.enc.Hex.parse parses the hexadecimal to bytes. CryptoJS.enc.Hex.parse将十六进制解析为字节。 The equivalent in Python is with codecs.decode("...", "hex") . Python 中的等效项是codecs.decode("...", "hex")

The salt also looks like hexadecimal but your JS doesn't parse it as such, so I've just treated it as UTF8 in the python as well. salt 也看起来像十六进制,但你的 JS 不会这样解析它,所以我也只是在 python 中将它视为 UTF8。

import hmac
import hashlib
import codecs

seed = codecs.decode(b"319aa8124bbcddac2bae8438cfd5e658aeca56d524736739622dfb0a09942b22", "hex")
salt = u"0000000000000000004d6ec16dafe9d8370958664c1dc422f452892264c59526".encode("utf8")
hm = hmac.new(salt, seed, hashlib.sha256)
h = hm.hexdigest()
print(h)   # returns fe6a57f08b9970b7cd497e627afac956203a8ef829d2d97c7967775c1c0b6f6a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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