Skip to main content

PersonalSign

Web3 调用实现签名

会唤起 metamask 签名

web3.eth.personal.sign(web3.utils.utf8ToHex(message), account);

直接调用 metamask 的签名

也会唤起 metamask 签名

function personalSign(web3,account,message) {
const msg = web3.utils.toHex(message);
const params = [msg, account];
return new Promise((resolve, reject) => {
web3.currentProvider.sendAsync(
{
method: "personal_sign",
params: params,
from: account,
},
(error, result) => {
if (error) {
reject(error);
} else {
resolve(result.result);
}
}
);
});
}

ethers调用实现

依赖库: https://github.com/MetaMask/eth-sig-util

  • 安装依赖
yarn add @metamask/eth-sig-util
  • 签名方法
export function personalSign({
privateKey,
data,
}: {
privateKey: Buffer;
data: unknown;
}): string {
if (isNullish(data)) {
throw new Error('Missing data parameter');
} else if (isNullish(privateKey)) {
throw new Error('Missing privateKey parameter');
}

const message = legacyToBuffer(data);
const msgHash = hashPersonalMessage(message);
const sig = ecsign(msgHash, privateKey);
const serialized = concatSig(toBuffer(sig.v), sig.r, sig.s);
return serialized;
}
  • 调用使用
const privateKey = Buffer.from(
'4af1bceebf7f3634ec3cff8a2c38e51178d5d4ce585c52d6043e5e2cc3418bb0',
'hex',
);
const message = "HelloWorld"
const sign = personalSign({
privateKey,
message
})