【发布时间】:2014-08-16 21:31:08
【问题描述】:
尝试在 Python 和 C++ 中计算 SHA-1 摘要时得到不同的结果。
Python 代码:
import hashlib
salt = 0xF0C020D239062F875C7BD8FB218D8102C9B37656F653E8DF0C655EF2D4A0CB61
password = 'pass1'
m = hashlib.sha1()
m.update( bytearray.fromhex(hex(salt)[2:-1]) )
m.update( password )
print m.hexdigest()
# output: e92f9504b2d46db0af7732c6e89e0260e63ae9b8
我从 C++ 代码中提取了一个 sn-p:
BigNumber salt, x;
Sha1Hash xhash;
uint8 password[] = "pass1";
// salt is received from a network packet (32 bytes)
// 2014-08-16 16:06:37 --> salt=F0C020D239062F875C7BD8FB218D8102C9B37656F653E8DF0C655EF2D4A0CB61
salt.SetBinary(lc.salt, 32);
xhash.UpdateData(salt.AsByteArray(), salt.GetNumBytes());
xhash.UpdateData(password, sizeof(password) - 1);
xhash.Finalize();
x.SetBinary(xhash.GetDigest(), xhash.GetLength());
logdebug("--> x=%s", x.AsHexStr());
// output: E5B463090B335BBC734BD3F4683F310E87ED6E4A
我必须如何修改我的 Python 代码才能获得与 C++ 中相同的结果?
【问题讨论】:
-
您的 python 代码不起作用。
hex(salt)[2:-1]你有奇数个字符。 -
@Daniel:不,这恰好可行,因为在 Python 2 中,该数字是一个长整数,并附加了一个
L。然而,为盐生成字节是一种可怕的方式。 -
在 Python 中定义盐的更好方法是使用
'F0C020D239062F875C7BD8FB218D8102C9B37656F653E8DF0C655EF2D4A0CB61'.decode('hex')。