在 near 协议中使用 ed25519 进行签名和验证

Sign and verify using ed25519 in near protocol

我正在尝试使用 signMessage and verify it with python for implementing 在 javascript 中签署消息。

这是使用 near-api-js

在 javascript 中签署消息的代码
window.signer = await new nearlib.InMemorySigner(window.walletAccount._keyStore)
const mysign = await window.signer.signMessage("Amiya", 
window.walletAccount._authData.accountId, window.walletAccount._networkId)
let mypubdata = ""
mysign.publicKey.data.forEach( function (item,index){
  if(item < 16) {
    mypubdata = mypubdata + '0' + item.toString(16)
  }
  else {
    mypubdata = mypubdata + item.toString(16)
  }

})
console.log("public key", mypubdata)
let mysignature = ""
mysign.signature.forEach( function (item,index){
  if(item < 16) {
    mysignature = mysignature + '0' + item.toString(16)
  }
  else {
    mysignature = mysignature + item.toString(16)
  }

})
console.log("signature", mysignature)

输出给出:
public 密钥 fe20d3e271876c8329c74dcdbe95e32586ee5cf67def1c0cc9e0b8d0e4285813
签名 61d864f40667075da6f920f811def3b83330a6cce49b7bd24eb4711f29abcf55d6d2eaf6f67bf74f20a2f79598f7fd42b4f70db41446d73d596b58d31825710c [=15]

这是我的 python 后端代码:

import ed25519
import hashlib
pubKey = ed25519.VerifyingKey(b"fe20d3e271876c8329c74dcdbe95e32586ee5cf67def1c0cc9e0b8d0e4285813", encoding="hex")

print("Public key (32 bytes): ", pubKey.to_ascii(encoding='hex'))
signature = "61d864f40667075da6f920f811def3b83330a6cce49b7bd24eb4711f29abcf55d6d2eaf6f67bf74f20a2f79598f7fd42b4f70db41446d73d596b58d31825710c"
msg = hashlib.sha256(b"Amiya").hexdigest()
print(msg)

try:
    pubKey.verify(signature, msg, encoding='hex')
    print("The signature is valid.")
except:
    print("Invalid signature!")

但我无法让它工作,它提供了一个无效的签名。

形式化@topaco 在上面的评论中给出的答案:

尝试 digest() 而不是 hexdigest() – Topaco 5 月 27 日 18:13