【问题标题】:Sign a text with pynacl (Ed25519) importing a private key使用 pynacl (Ed25519) 导入私钥签署文本
【发布时间】:2022-07-14 23:53:46
【问题描述】:

在下面的代码中,我尝试使用 pynacl 签署随机数。

from nacl.encoding import Base64Encoder
from nacl.signing import SigningKey
import base58
import base64

secret = '5N3SxG4UzVDpNe4LyDoZyb6bSgE9tk3pE2XP5znXo5bF'
nonce = '3eaf8814caa842d94fdb96fc26d02f7c339e65ff'

h=hashlib.new('sha256')
h.update(str.encode(nonce))
hashednonce = h.hexdigest()

key = base58.b58decode(secret)
signingkey = SigningKey(key)

signednonce = signingkey.sign(hashednonce.encode())

该密钥在 base58 中(别担心,它不是我的,公开发布在 here)。在那个页面中也是它应该输出的签名,但它不一样。

恐怕密钥导入方式错误

【问题讨论】:

    标签: python python-3.x ed25519 nacl-cryptography pynacl


    【解决方案1】:

    使用的 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 示例中的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-30
      • 2011-10-15
      • 1970-01-01
      • 2014-12-17
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      • 1970-01-01
      相关资源
      最近更新 更多