you can use the ecrecover function in Solidity. The ecrecover function will return Ethereum address associated with the public key that signed the data, but you can then compare this address with the one derived from the public key you provided.
smart contract code that contains a public key and verify function:
contract SignatureVerifier {
bytes32 public publicKey;
constructor(bytes32 _publicKey) {
publicKey = _publicKey;
}
function verify(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) public view returns (bool) {
address recoveredAddress = ecrecover(hash, v, r, s);
address publicKeyAddress = address(uint160(uint256(publicKey)));
key
return recoveredAddress == publicKeyAddress;
}
}
The verify function takes the hash of the message that was signed, and the signature components v, r, and s. The ecrecover function is used to recover the Ethereum address associated with the public key that was used to sign the data. Then, the function compares this recovered address with the one derived from the provided public key.
Please note that this example assumes that the provided public key is indeed related to an Ethereum address.
Offchain code to sign the data:
async function signData() {
const accounts = await web3.eth.getAccounts();
const account = accounts[0];
const data = 'your data';
// Hash the data
const dataHash = web3.utils.keccak256(data);
web3.eth.personal.sign(dataHash, account, (error, signature) => {
if (error) {
console.error('Error signing data:', error);
} else {
console.log('Signature:', signature);
const r = signature.slice(0, 66);
const s = '0x' + signature.slice(66, 130);
const v = '0x' + signature.slice(130, 132);
const v_decimal = web3.utils.toDecimal(v);
console.log('v:', v_decimal);
console.log('r:', r);
console.log('s:', s);
}
});
}
If you are looking for typed data signature verification, you can refer to my this answer Verifying signed typed message hash on-chain.
Please accept and upvote if it helps
publicKeyAddress = address(uint160(uint256(publicKey))). See the correct formula in this answer https://ethereum.stackexchange.com/a/29480. – Ismael Apr 18 '23 at 00:22