简体   繁体   English

python HMAC中的填充不对吗?

[英]Isn't the padding in python HMAC wrong?

At the top of hmac.py are the lines: 这些行在hmac.py的顶部:

trans_5C = "".join ([chr (x ^ 0x5C) for x in xrange(256)])
trans_36 = "".join ([chr (x ^ 0x36) for x in xrange(256)])

But the HMAC RFC (and every other source I could find) states that the inner and outer padding should be the bytes 0x5C and 0x36 repeated, not XORed with a range of numbers. 但是HMAC RFC (以及我可以找到的所有其他来源)指出,内部和外部填充应为重复的字节0x5C和0x36,而不是与一定范围的数字进行异或。 That is, I expect to see: 也就是说,我希望看到:

trans_5C = chr(0x5C) * 256
trans_36 = chr(0x36) * 256

What am I missing? 我想念什么?

It's not incorrect. 这是不对的。 The code applies an optimization that is non-oblivious. 该代码应用了非显而易见的优化。

The code: 编码:

trans_5C = "".join ([chr (x ^ 0x5C) for x in xrange(256)])
trans_36 = "".join ([chr (x ^ 0x36) for x in xrange(256)])

Actually computes translation strings that are latter use to perform the XOR operations for the inner and outer padding. 实际计算转换字符串,该字符串随后用于对内部和外部填充执行XOR操作。 The code latter in the HMAC class's __init__ does the XOR operations indirectly via the translate function and the precomputed strings: HMAC类的__init__中后面的代码通过转换函数和预先计算的字符串间接进行XOR操作:

    self.outer.update(key.translate(trans_5C))
    self.inner.update(key.translate(trans_36))

Lets then look at what key.translate(trans_5C) does: 然后看一下key.translate(trans_5C)作用:

str.translate(table[, deletechars])

Return a copy of the string where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. 返回字符串的副本,其中删除了在可选参数deletechars中出现的所有字符,并且其余字符已通过给定的转换表进行映射,该转换表的长度必须为256。

It can be shown that key.translate(trans_5C) is an optimized version of: 可以看出key.translate(trans_5C)是以下内容的优化版本:

''.join(chr(ord(k) ^ 0x5C) for k in key)

Thereby: 从而:

>>> trans_5C = "".join ([chr (x ^ 0x5C) for x in xrange(256)])
>>> key = '0123456789'
>>> key.translate(trans_5C)
'lmnohijkde'
>>> ''.join(chr(ord(k) ^ 0x5C) for k in key)
'lmnohijkde'

The value of those two expressions is the same. 这两个表达式的值相同。 The same holds if 0x5C is replaced with 0x36 . 如果将0x5C替换为0x36则同样适用。

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

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