Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Update sign-message.md to include v2 examples
Browse files Browse the repository at this point in the history
metasal1 authored Nov 19, 2024
1 parent 5eb7bb5 commit 94812d8
Showing 1 changed file with 36 additions and 11 deletions.
47 changes: 36 additions & 11 deletions content/cookbook/wallets/sign-message.md
Original file line number Diff line number Diff line change
@@ -8,22 +8,44 @@ The primary function of a keypair is to sign messages and enable verification of
the signature. Verification of a signature allows the recipient to be sure that
the data was signed by the owner of a specific private key.

To do so, we can use the [TweetNaCl](https://www.npmjs.com/package/tweetnacl)
crypto library:
For Solana Web3.js v1, we can use the
[TweetNaCl](https://www.npmjs.com/package/tweetnacl) crypto library:

```typescript filename="sign-message.ts"
<Tabs groupId="language" items={['web3.js v2', 'web3.js v1']}>

<Tab value="web3.js v2">

```typescript
import { generateKeyPair, signBytes, verifySignature } from "@solana/keys";
import { getUtf8Encoder, getBase58Decoder } from "@solana/codecs";

const keys = await generateKeyPair();

const message = getUtf8Encoder().encode(
"The quick brown fox jumps over the lazy dog",
);
const signedBytes = await signBytes(keys.privateKey, message);

console.log("Signature:", getBase58Decoder().decode(signedBytes));

const verifiedSignature = await verifySignature(
keys.publicKey,
signedBytes,
message,
);

console.log("Verified:", verifiedSignature);
```

</Tab>
<Tab value="web3.js v1">

```typescript
import { Keypair } from "@solana/web3.js";
import nacl from "tweetnacl";
import { decodeUTF8 } from "tweetnacl-util";

const keypair = Keypair.fromSecretKey(
Uint8Array.from([
174, 47, 154, 16, 202, 193, 206, 113, 199, 190, 53, 133, 169, 175, 31, 56,
222, 53, 138, 189, 224, 216, 117, 173, 10, 149, 53, 45, 73, 251, 237, 246,
15, 185, 186, 82, 177, 240, 148, 69, 241, 227, 167, 80, 141, 89, 240, 121,
121, 35, 172, 247, 68, 251, 226, 218, 48, 63, 176, 109, 168, 89, 238, 135,
]),
);
const keypair = Keypair.generate();

const message = "The quick brown fox jumps over the lazy dog";
const messageBytes = decodeUTF8(message);
@@ -37,3 +59,6 @@ const result = nacl.sign.detached.verify(

console.log(result);
```

</Tab>
</Tabs>

0 comments on commit 94812d8

Please sign in to comment.