Last active
February 27, 2025 22:50
-
-
Save SBub/37780d002b330f416a7617b0b7c1a680 to your computer and use it in GitHub Desktop.
Verify signature of a signed message
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // sign a message with a wallet private key and validate its signature | |
| // https://github.com/0xC0A1/web3-auth/tree/master | |
| import { useEffect } from "react"; | |
| import b58 from "bs58"; | |
| import nacl from "tweetnacl"; | |
| import { PublicKey } from "@solana/web3.js"; | |
| import { useWallet } from "@solana/wallet-adapter-react"; | |
| export const Sign = () => { | |
| const { signMessage, publicKey } = useWallet(); | |
| const getSignature = async (str: string) => { | |
| const encodedMessage = new TextEncoder().encode(str); | |
| const signature = await signMessage(encodedMessage); | |
| const pk = publicKey.toBase58(); | |
| const msg = b58.encode(encodedMessage); | |
| const sig = b58.encode(signature); | |
| return `${pk}.${msg}.${sig}`; | |
| }; | |
| const verifySignature = async (authToken: string) => { | |
| const [pk, msg, sig] = authToken.split("."); | |
| const hasValidSig = nacl.sign.detached.verify( | |
| b58.decode(msg), | |
| b58.decode(sig), | |
| new PublicKey(pk).toBytes() | |
| ); | |
| return hasValidSig; | |
| }; | |
| useEffect(() => { | |
| if (publicKey) { | |
| getSignature("hello world") | |
| .then((signature) => { | |
| console.log("signature", signature); | |
| // verify signature | |
| return verifySignature(signature); | |
| }) | |
| .then((isValid) => { | |
| console.log("is signature valid", isValid); | |
| }) | |
| .catch((e) => console.error("error getting signature", e)); | |
| } | |
| }, [publicKey]); | |
| return null; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment