Summary
- A keypair consists of a matching public key (used as an address) and a secret key (used for verification).
- Public keys can be shared openly, while secret keys must remain confidential.
@solana/web3.js
provides tools for generating new keypairs or reconstructing them from existing secret keys.
Lesson
This lesson explores cryptography fundamentals and their application in the Solana ecosystem.
Symmetric and Asymmetric Cryptography
Cryptography involves methods for securing information. The two primary types are:
Symmetric Cryptography
- Uses a single key for encryption and decryption.
- Common algorithms: AES and Chacha20.
Asymmetric Cryptography
- Uses keypairs (public + secret keys).
Enables:
- Encryption: Data encrypted with a public key can only be decrypted by the paired secret key.
- Signatures: Data signed with a secret key can be verified with the paired public key.
- Key exchange: Derives session keys for symmetric encryption.
- Common algorithms: ECC and RSA.
Solana Uses Public Keys as Addresses
- Public keys serve as wallet addresses (e.g.,
dDCQNnDmNbFVi8cQhKAgXhyhXeJ625tvwsunRyRc7c8
). - Secret keys authorize transactions—keep them secure!
Using @solana/web3.js
to Create a Keypair
Install the library:
npm i @solana/web3.js@1
Generate a new keypair:
import { Keypair } from "@solana/web3.js";
const keypair = Keypair.generate();
console.log("Public key:", keypair.publicKey.toBase58());
console.log("Secret key:", keypair.secretKey);
👉 Never store secret keys in source code. Use .env
files instead.
Loading an Existing Keypair
Use helper functions to load keys securely:
npm i @solana-developers/helpers
From an .env
file:
import "dotenv/config";
import { getKeypairFromEnvironment } from "@solana-developers/helpers";
const keypair = getKeypairFromEnvironment("SECRET_KEY");
Lab
Installation
Set up a project:
mkdir generate-keypair
cd generate-keypair
npm init -y
npm install typescript @solana/web3.js@1 esrun @solana-developers/helpers@2
Create generate-keypair.ts
:
import { Keypair } from "@solana/web3.js";
const keypair = Keypair.generate();
console.log("Public key:", keypair.publicKey.toBase58());
console.log("Secret key:", keypair.secretKey);
Run:
npx esrun generate-keypair.ts
Secure Key Storage
Store the secret key in
.env
:SECRET_KEY="[your_secret_key]"
Load it securely:
import "dotenv/config"; import { getKeypairFromEnvironment } from "@solana-developers/helpers"; const keypair = getKeypairFromEnvironment("SECRET_KEY");
FAQ
Why is asymmetric cryptography important in Solana?
It ensures secure transactions and data integrity by using keypairs for encryption and signatures.
How do I protect my secret key?
Store it in .env
files, exclude them from version control (e.g., .gitignore
), and avoid hardcoding.
Can I regenerate a keypair from a secret key?
Yes—the public/secret keypair can be reconstructed from the secret key alone.