2

我正在尝试使用signMessage在 javascript 中对消息进行签名,并使用 python 对其进行验证以实现jwt authentication

这是使用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)

Output gives:
public key fe20d3e271876c8329c74dcdbe95e32586ee5cf67def1c0cc9e0b8d0e4285813
signature 61d864f40667075da6f920f811def3b83330a6cce49b7bd24eb4711f29abcf55d6d2eaf6f67bf74f20a2f79598f7fd42b4f70db41446d73d596b58d31825710c

这是我的后端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!")

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

4

1 回答 1

0

将@topaco 在上述评论中给出的答案正式化:

尝试digest()代替hexdigest()– Topaco 5 月 27 日 18:13

于 2020-06-03T20:54:00.060 回答