使用的 NodeJS 库的 sign() 方法需要十六进制编码的密钥和消息,请参阅 here。十六进制格式是这个特定库的一个特殊特征。
相比之下,PyNaCl 期望两者都是像对象一样的字节,请参阅here。对于键,这已经满足,因为b58decode() 将数据作为字节返回,如对象。对于随机数的散列,最简单的方法是使用digest() 而不是hexdigest(),然后散列后的随机数也作为对象返回为字节。
sign() 在 Python 代码中返回的结果由 64 字节签名和散列随机数的串联组成,即前 64 个字节对应于 NodeJS 示例中的签名。
完整代码:
from nacl.signing import SigningKey
import base58
import hashlib
secret = '5N3SxG4UzVDpNe4LyDoZyb6bSgE9tk3pE2XP5znXo5bF'
nonce = '3eaf8814caa842d94fdb96fc26d02f7c339e65ff'
h = hashlib.new('sha256')
h.update(nonce.encode('utf-8'))
hashednonce = h.digest()
key = base58.b58decode(secret)
signingkey = SigningKey(key)
signednonce = signingkey.sign(hashednonce)
print("Hashed nonce, hex: " + hashednonce.hex())
print("Signature | hashed nonce, hex: " + signednonce.hex())
print("Signature, hex: " + signednonce[:64].hex())
输出:
Hashed nonce, hex: 6d748f209e5af1f5b8825f7822d6659c45c874076cd2b3337c7861fd94cd3ba5
Signature | hashed nonce, hex: 270c2e502c5c753e39159683981e452444f81a10d798f56406a9c471d672a5ede1792cb7f97d4f9c9efeec7bf35577dd1f8482afca7e3710291868a65bf91e076d748f209e5af1f5b8825f7822d6659c45c874076cd2b3337c7861fd94cd3ba5
Signature, hex: 270c2e502c5c753e39159683981e452444f81a10d798f56406a9c471d672a5ede1792cb7f97d4f9c9efeec7bf35577dd1f8482afca7e3710291868a65bf91e07
可以看出,散列的 nonce 和签名对应于 NodeJS 示例中的值。