Hedera 消息签名验证的未公开秘密
发布: (2026年2月21日 GMT+8 21:23)
2 分钟阅读
原文: Dev.to
Source: Dev.to
问题
我在 Hedera 上构建一个 P2P NFT 交换。所有功能都正常,但消息签名验证一直失败。
// Frontend
const signature = await wallet.signMessage("Sign in to MichiMint");
// Backend
const isValid = pubKey.verify(
Buffer.from("Sign in to MichiMint"),
signature
);
// false ❌
相同的消息、全新的签名、正确的公钥——为什么验证结果是 false?
解决方案
Hedera 钱包会在签名的消息前面添加一个隐藏前缀。
function prefixMessage(message: string): string {
return '\x19Hedera Signed Message:\n' + message.length + message;
}
使用带前缀的消息进行验证:
// Backend verification
const prefixedMessage = prefixMessage("Sign in to MichiMint");
const isValid = pubKey.verify(Buffer.from(prefixedMessage), signature);
// true ✅
解释
\x19– 魔术字节,用于防止交易哈希冲突。Hedera Signed Message:\n– 上下文标识符。22– 原始消息的长度("Sign in to MichiMint")。- 原始消息随后跟随。
Hedera 采用了以太坊的 EIP‑191 标准来对消息进行签名,默认开发者会了解这个前缀。若不加入前缀,签名可能在不同上下文中被重放,从而不安全。
影响
此发现为 MichiMint 提供了动力——它是基于 Hedera 的首个无需信任的 P2P NFT 交换,使用了计划交易(Scheduled Transactions)。